Friday, April 2, 2010

WPF show or hide element based on CheckBox

  Today I had to do the task for showing or hiding elements based the value of a checkbox. In WinForms 2.0 for this purpose it was necessary to subscribe to event CheckedChanged and in his handler write the code:

private void myCheckBox_CheckedChanged(object sender, EventArgs e)
{
  myTextBox.Visible = myCheckBox.Checked;
}

  With the new Visibility Enum in WPF, this becomes a bit trickier. To accomplish this, you can use converter BooleanToVisibilityConverter that accept a boolean value and return a visibility value. Now we can cleanly show or hide an element based on a checkbox using just XAML code. The XAML code to use this is below:

<Window
  x:Class="MyTest.XamlOnly"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="XamlOnly" Height="300" Width="300">

  <Window.Resources>
    <BooleanToVisibilityConverter x:Key="BoolToVisConverter" />
  </Window.Resources>

  <StackPanel Orientation="Vertical">
    <CheckBox Content="Check to show text box below me" Name="checkViewTextBox"/>
    <TextBox Text="only seen when above checkbox is checked" Visibility="{Binding Path=IsChecked, ElementName=checkViewTextBox, Converter={StaticResource BoolToVisConverter}}"/>
  </StackPanel>

</Window>

2 comments:

  1. What do you do when you want to show textbox when checkbox is not checked?

    ReplyDelete
  2. If you want always to show textbox, you will need to remove binding to Visibility(Visibility="{Binding Path=IsChecked, ElementName=checkViewTextBox, Converter={StaticResource BoolToVisConverter}}").

    ReplyDelete