Close this search box.

WPF – Show/Hide element based on CheckBox.Checked

A lot of times, I need to show or hide a textbox based the value of a checkbox.


In WinForms 2.0.  This was easy:

myTextBox.Visible = myCheckBox.Checked;

With the new Visibility Enum in WPF, this becomes a bit trickier.  To accomplish this, you need to implement a converter that will accept a boolean value and return a visibility value.  The converter I used is here:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Data;
using System.Windows;

namespace ParaPlan.Converters {
  public class BooleanToHiddenVisibility : IValueConverter {
    public object Convert(object value, Type targetType, object parameter,
                          System.Globalization.CultureInfo culture) {
      Visibility rv = Visibility.Visible;
      try {
        var x = bool.Parse(value.ToString());
        if (x) {
          rv = Visibility.Visible;
        } else {
          rv = Visibility.Collapsed;
      } catch (Exception) {
      return rv;

    public object ConvertBack(object value, Type targetType, object parameter,
                              System.Globalization.CultureInfo culture) {
      return value;

The XAML code to use this is below.  The important parts are:
converters:BooleanToHiddenVisibility x:Key=”boolToVis”
TextBox … Visibility={Binding Path=IsChecked, ElementName=checkViewTextBox…}”

<Window x:Class="ParaPlan.Windows.Window1"
    Title="Window1" Height="300" Width="300"
    <StackPanel Orientation="Vertical">
            <converters:BooleanToHiddenVisibility x:Key="boolToVis"/>
        <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 boolToVis}}"/>

Now we can cleanly show or hide an element based on a checkbox using just XAML code.

Technorati tags: WPFXAMLconverter

Print | posted on Monday, December 10, 2007 11:24 AM | Filed Under [ .NETWPF ]

This article is part of the GWB Archives. Original Author: Tim Hibbard

Related Posts