Databinding the Visibility property in Silverlight
In most of the languages you have been exposed to, a UI element being displayed or not was probably related to some Boolean property. It was black or white, true or false (Duality anyone?).
WPF adds a third possibility all of which are contained in the Visibility enumeration. The possible values (in WPF) are:
- Visible: Display the element.
- Hidden: Do not display the element, but reserve space for the element in layout.
- Collapsed: Do not display the element, and do not reserve space for it in layout.
Silverlight does not support the Hidden state of the enumeration so you are back to true or false but to preserve compatibility with WPF we use the enumeration.
You may run across the need to show or hide an element based on the value of a boolean variable as I recently did. I found that data binding and a converter will do the trick. I found a useful converter by Nick Kramer and wrote a quick-n-dirty proof of concept app which you may find helpful as it’s a MVVM app with an element in the View whose Visibility depends on a variable in the ViewModel. The app runs like this:
Your browser does not support iframes.
The usage pattern is to make the Converter available as a Resource then use a Binding Markup Extension to bind the Visibility property as follows.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <UserControl x:Class="VisibilityBindingTest.View.SilverlightControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:convert="clr-namespace:Converters"> <UserControl.Resources> <convert:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" /> </UserControl.Resources> <Grid x:Name="LayoutRoot" Background="White"> <Grid.RowDefinitions> <RowDefinition Height="200"/> <RowDefinition Height="50"/> </Grid.RowDefinitions> <Grid Background="Red" Width="100" Height="100" Visibility="{Binding Path=BoolVisilibity, Converter={StaticResource BoolToVisibilityConverter}}"/> <Button Content="toggle red grid..." Click="Button_Click" Grid.Row="1" HorizontalAlignment="Center"/> </Grid> </UserControl>verticalAlign="middle"> |
The Visual Studio solution is
available here – Cheers!
[...] Databinding the Visibility property in Silverlight [...]