Bind The Visibility Of A Control Based On The Property Of RadioButton or CheckBox

If you want to control the visibility of a control like textblock/textbox, etc. based on the Checked or Unchecked Property of RadioButton/Checkbox , then you can use the inbuilt ‘BooleanToVisibilityConverter’ to achieve this easily. This will prevent you to write longer codes to control the visibility from CodeBehind pages. This is useful, for example, when you want to hide a certain control when a checkbox is checked and hide that control when the checkbox is unchecked.

Steps:

  1. First of all define the following code inside the <Application.Resources> </Application.Resources> tag of the App.XAML page.
    1. <local:BooleanToVisibilityConverter x:Key="MyConverter1"/>  
    code

    It is necessary to provide a key to this converter. I have given it a key of MyConverter1 . We will access this converter by using this Key from this point onwards.

  2. Now suppose, I have a Checkbox Control as in the following snippet whose Name is MyCheckBoxControl
    <CheckBox x:Name="MyCheckBoxControl" Content="My Check Box”/>
    .

  3. Similarly I have a TextBox which I want to make visible only when the CheckBox above is checked, i.e whenever IsChecked property of CheckBox is set to ‘True’. We will bind the TextBox control to the CheckBox as in the following code snippet:
    1. <TextBox x:Name="MyTextBox" Visibility="{Binding ElementName=MyCheckBox,Path=IsChecked,Converter={StaticResource MyConverter1}}" />  
    TextBox

    Here, the Visibility Property of the TextBox is binded to an ‘ElementName=MyCheckBox’ which is our Checkbox name. The ‘Path=IsChecked’ is the property which we want to be true in order to hide the TextBox and the ‘Converter={StaticResource MyConverter1}’ is the Converter that we implement to hide our TextBox.

    This gets our job done without even having to visit the CodeBehind pages.

How the Converter Works and why it is necessary?

We know, a ‘Visibility’ property only takes its value as either Visiblity.Visible or Visibility.Collapsed.
And we also know that a ‘checkbox’(or a RadioButton)’s IsChecked Property only takes its value as either ‘true’ or ‘false’.

Since a visibility property cannot take ‘true’ or ‘false’ value, so in order to assign the Visibility property’s value as Visibility.Visible or Visibility.Collapsed based on either ‘true’ or ‘false’ property of the CheckBox, we need a Converter. This Converter as its name implies converts the ‘true’ value to ‘Visibility.Visible’ and ‘false’ value to ‘Visibility.Collapsed’ and hence allows the binding to happen easily.


Recommended Free Ebook
Similar Articles