Binding visibility of a control to 'Count' of an IEnumerable

前端 未结 3 1725
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-19 08:55

I have a list of objects contained in an IEnumerable<>. I would like to set the visibility of a control based on the count of this list. I have tried:

 Visibi         


        
相关标签:
3条回答
  • 2021-02-19 09:39

    You should use a converter, which converts the Count property to a Visibility value, or perhaps a new "HasItems" boolean property to a Visibility value. We use something, for example, called boolToVisibilityConvert, to handle jobs like this.

    I can give you more precise details, if you need them.

    0 讨论(0)
  • 2021-02-19 09:43

    There is three ways:

    1. to use Triggers mentioned by H.B.
    2. to use convertors by implementing IValueConverter in a class and setting the Converter property of Binding to an instance of IValueConverter in that class
    3. to define a property in your ViewModel to directly return the Visibility state.

    You could always use Triggers method and it always is a good approach. The third method is useful(and is best) when you are using MVVM pattern (and you are not restricting yourself from referencing UI related assemblies in your ViewModel) I suggest using Triggers, but if you dont want to make your xaml dirty by that much markup codes use converters.

    0 讨论(0)
  • 2021-02-19 09:58

    You cannot use logical or code-expressions in bindings (it expects a PropertyPath). Either use a converter or triggers, which is what i would do:

    <YourControl.Style>                     
        <Style TargetType="YourControl">
            <Setter Property="Visibility" Value="Collapsed" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding MyList.Count}" Value="0">
                    <Setter Property="Visibility" Value="Visible" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </YourControl.Style>
    

    (You can of course refactor the style into a resource if you wish.)

    0 讨论(0)
提交回复
热议问题