How to: Change the Visibility Property
Example
This example shows how to change the value of the Visibility property.
The first example, which is Extensible Application Markup Language (XAML), defines a TextBox and places it in a StackPanel element. Three Button controls represent the three enumeration values of the Visibility property: Visible, Hidden, and Collapsed. When a user clicks any of these buttons, the click triggers an event in the code-behind file that is associated with the Button. The Visibility state of the TextBox is changed to match the value associated with the Button.
<Border BorderBrush="Black" BorderThickness="2" Background="White">
<DockPanel>
<TextBlock FontSize="20" FontWeight="Bold" DockPanel.Dock="Top" Margin="0,0,0,10">UIElement.Visibility Sample</TextBlock>
<TextBlock DockPanel.Dock="Top" Margin="0,0,0,10">Click the buttons below to manipulate the Visibility property of the TextBox below.</TextBlock>
<StackPanel DockPanel.Dock="Left">
<Button Name="btn1" Height="25" Click="contentVis">Visibility="Visible"</Button>
<Button Name="btn2" Height="25" Click="contentHid">Visibility="Hidden"</Button>
<Button Name="btn3" Height="25" Click="contentCol">Visibility="Collapsed"</Button>
</StackPanel>
<StackPanel HorizontalAlignment="Center">
<TextBox Name="tb1" Width="100" Height="50">A TextBox</TextBox>
<TextBlock Name="txt1" TextWrapping="Wrap" FontSize="14"/>
</StackPanel>
</DockPanel>
</Border>
The following code-behind file handles the Button Click events that the previous XAML example defines.
Private Sub contentVis(ByVal sender As Object, ByVal args As RoutedEventArgs)
tb1.Visibility = System.Windows.Visibility.Visible
txt1.Text = "Visibility is now set to Visible."
End Sub
Private Sub contentHid(ByVal sender As Object, ByVal args As RoutedEventArgs)
tb1.Visibility = System.Windows.Visibility.Hidden
txt1.Text = "Visibility is now set to Hidden. Notice that the TextBox still occupies layout space."
End Sub
Private Sub contentCol(ByVal sender As Object, ByVal args As RoutedEventArgs)
tb1.Visibility = System.Windows.Visibility.Collapsed
txt1.Text = "Visibility is now set to Collapsed. Notice that the TextBox no longer occupies layout space."
End Sub
private void contentVis(object sender, RoutedEventArgs e)
{
tb1.Visibility = System.Windows.Visibility.Visible;
txt1.Text = "Visibility is now set to Visible.";
}
private void contentHid(object sender, RoutedEventArgs e)
{
tb1.Visibility = System.Windows.Visibility.Hidden;
txt1.Text = "Visibility is now set to Hidden. Notice that the TextBox still occupies layout space.";
}
private void contentCol(object sender, RoutedEventArgs e)
{
tb1.Visibility = System.Windows.Visibility.Collapsed;
txt1.Text = "Visibility is now set to Collapsed. Notice that the TextBox no longer occupies layout space.";
}