A lot of times, I need to show or hide a textbox based the value of a checkbox.
myTextBox.Visible = myCheckBox.Checked;
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;
}
}
}
<Window x:Class="ParaPlan.Windows.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
xmlns:converters="clr-namespace:ParaPlan.Converters">
<StackPanel Orientation="Vertical">
<StackPanel.Resources>
<converters:BooleanToHiddenVisibility x:Key="boolToVis"/>
</StackPanel.Resources>
<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}}"/>
</StackPanel>
</Window>
Now we can cleanly show or hide an element based on a checkbox using just XAML code.