ValueConverterを使って型の異なるプロパティとバインドする
チェックボックスを使って特定のコントロールを非活性化させたり、非表示にしたりするということは結構よくあることかと思います。WPFではプロパティどうしを簡単にバインディングする方法が用意されていますので、わざわざイベントハンドラを書かなくともこの方法を使って実現することができます。
非活性化させるIsEnabledプロパティはBoolean型ですので、同じBoolean型であるチェックボックスのIsCheckedプロパティとそのままバインディングすることができます。※正確にはIsCheckedプロパティはNullable(Of Boolean)型で、最初からNullableBoolConverterが用意されています。
一方非表示にするVisibilityプロパティは以前の投稿でもご紹介したように、Boolean型ではなくVisibility列挙体となっており、Visible、Collapsed、Hiddenという3つの値を設定するようになっています。
このような異なる型どうしをバインディングするために、バインディングにはコンバータを指定することができるようになっています。今回の場合に使うコンバータはBooleanToVisibilityConverterです。
XAML
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xml:lang="ja-JP"
x:Class="Window1"
x:Name="Window"
Title="Window1"
Width="200" Height="200" FontSize="24">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="0.3*"/>
<RowDefinition Height="0.3*"/>
<RowDefinition Height="0.3*"/>
</Grid.RowDefinitions>
<Button Content="Button" IsEnabled="{Binding Path=IsChecked, ElementName=CheckBox1}" HorizontalAlignment="Center" VerticalAlignment="Center" Visibility="{Binding Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}, ElementName=CheckBox2}"/>
<CheckBox HorizontalAlignment="Center" Margin="10,10,10,10" VerticalAlignment="Center" Content="IsEnabled" Grid.Row="1" x:Name="CheckBox1" IsChecked="True"/>
<CheckBox Content="Visibility" HorizontalAlignment="Center" Margin="10,10,10,10" x:Name="CheckBox2" VerticalAlignment="Center" Grid.Row="2" IsChecked="True" />
</Grid>
</Window>
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xml:lang="ja-JP"
x:Class="Window1"
x:Name="Window"
Title="Window1"
Width="200" Height="200" FontSize="24">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="0.3*"/>
<RowDefinition Height="0.3*"/>
<RowDefinition Height="0.3*"/>
</Grid.RowDefinitions>
<Button Content="Button" IsEnabled="{Binding Path=IsChecked, ElementName=CheckBox1}" HorizontalAlignment="Center" VerticalAlignment="Center" Visibility="{Binding Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}, ElementName=CheckBox2}"/>
<CheckBox HorizontalAlignment="Center" Margin="10,10,10,10" VerticalAlignment="Center" Content="IsEnabled" Grid.Row="1" x:Name="CheckBox1" IsChecked="True"/>
<CheckBox Content="Visibility" HorizontalAlignment="Center" Margin="10,10,10,10" x:Name="CheckBox2" VerticalAlignment="Center" Grid.Row="2" IsChecked="True" />
</Grid>
</Window>
Blendで設定する場合、[データのバインドの作成]ダイアログで表示を[一致する型のみ]から[すべてのプロパティ]に変更することで型の異なるプロパティを選択することができます。IsCheckedプロパティを選択したら、[値コンバータ]にBooleanToVisibilityConverterを指定して完了です。