Binding to a WPF ToggleButton's IsChecked state
binding, togglebutton, wpf, xaml
Solution
You need to bind the `Visibility` through a converter:
<Window
x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>
<StackPanel>
<ToggleButton x:Name="toggleButton" Content="Toggle"/>
<TextBlock
Text="Some text"
Visibility="{Binding IsChecked, ElementName=toggleButton, Converter={StaticResource BooleanToVisibilityConverter}}"/>
</StackPanel>
</Window>
In Silverlight there is no `BooleanToVisibilityConverter` but it is easy to write your own with some added features:
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace WpfApplication1 {
public class BooleanToVisibilityConverter : IValueConverter {
public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture) {
if (targetType == typeof(Visibility)) {
var visible = System.Convert.ToBoolean(value, culture);
if (InvertVisibility)
visible = !visible;
return visible ? Visibility.Visible : Visibility.Collapsed;
}
throw new InvalidOperationException("Converter can only convert to value of type Visibility.");
}
public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture) {
throw new InvalidOperationException("Converter cannot convert back.");
}
public Boolean InvertVisibility { get; set; }
}
}
Now you can specify a converter that maps `true` to `Collapsed` and `false` to `Visible`:
<BooleanToVisibilityConverter
x:Key="InverseBooleanToVisibilityConverter" InvertVisibility="True"/>
Problem
I would like to use a WPF `ToggleButton` to expand and collapse some controls in my application. How can I use XAML to accomplish this? I'm thinking that I could somehow bind the `Visibility` attribute of some controls to the `ToggleButton`'s `IsChecked` state, but I do not know how to do this. Maybe I need to give my `ToggleButton` a `Name`, then bind using `ElementName`? Then I would need a `ValueConverter` for converting between a boolean value and a Visibility, correct? How could I make a generic `ValueConverter` for this purpose?