#493 – Setting the Visibility of a User Interface Element
February 13, 2012 2 Comments
You can set the visibility of any element that inherits from UIElement by settings its Visibility property to one of the three values listed below. Because every child hosted in a panel derives from UIElement, this is how you hide/show child elements in a panel.
Values for Visibility (of type System.Windows.Visibility):
- Visible – element is displayed
- Hidden – element is not displayed, but the space where it is located is preserved
- Collapsed – element is not displayed and space for it is not preserved
Below is an example that lets a user toggle between the three possible values for the Visibility of the middle Label.
<StackPanel> <StackPanel Orientation="Horizontal" Margin="10"> <Label Content="Snoopy" Margin="3" Background="BurlyWood"/> <Label Content="Waldo" Margin="3" Background="Thistle" Visibility="{Binding ElementName=cboVisibility, Path=SelectedValue, Converter={StaticResource cboVisibilityConverter}}"/> <Label Content="Dagwood" Margin="3" Background="LightGreen"/> </StackPanel> <ComboBox Name="cboVisibility" HorizontalAlignment="Center" SelectedIndex="0"> <ComboBox.Items> <ComboBoxItem Content="Visible"/> <ComboBoxItem Content="Collapsed"/> <ComboBoxItem Content="Hidden"/> </ComboBox.Items> </ComboBox> <Label Content="Select visibility of middle Label" HorizontalAlignment="Center"/> </StackPanel>