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:
Visibility="{Binding MyList.Count>0?Collapsed:Visible, Mode=OneWay}"
But this doesn't work. I tried binding MyList.Count to the text in a text block to ensure that the count value was correct, and it is. It just doesn't seem to set the visibility correctly.
Data binding is a mechanism in WPF applications that provides a simple and easy way for Windows Runtime apps to display and interact with data. In this mechanism, the management of data is entirely separated from the way data. Data binding allows the flow of data between UI elements and data object on user interface.
Advertisements. Data binding is a mechanism in XAML applications that provides a simple and easy way for Windows Runtime Apps using partial classes to display and interact with data. The management of data is entirely separated from the way the data is displayed in this mechanism.
When an object is assigned to an object variable of the specific type, then the C# compiler performs the binding with the help of . NET Framework. C# performs two different types of bindings which are: Early Binding or Static Binding. Late Binding or Dynamic Binding.
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.)
There is three ways:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With