bool型の変数値を反転させて、コントロールにバインディングしたいとき
たとえば、ONボタンとOFFボタンをトグルさせたい場合があります。
ONボタンのIsEnabledとOFFボタンのIsEnabledが反転するようにすればいいのですが、どうすればよいのでしょうか?
答えは簡単です。Converterを使用するのです。
<!--GUIのXAML--> <Button x:Name="BtnOn" Content="ON" IsEnabled="True"/> <Button x:Name="BtnOff" Content="OFF" IsEnabled="{Binding ElementName=BtnOn, Path=IsEnabled, Converter={StaticResource BoolNeg}}"/>
Converterを指定すると、テキストで入力した文字列をEnum型やBool型に変換したり、その逆もできてしまいます。
今回は単純にTrue/Falseを反転させるだけの簡単なものなので、Converterは以下のようになります。
/// <summary> /// GUIのバインディングで、bool値を反転してくれるコンバーター /// </summary> public class CBoolNegativeConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return !(value is bool && (bool)value); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return !(value is bool && (bool)value); } }
また、Converter={StaticResource BoolNeg}のように指定していますので、例えば、どのソースからでも参照できるようにApp.xamlに以下のように追記します。
<Application x:Class="BoolNegTest.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:BoolNegTest"> <Application.Resources> <ResourceDictionary> <local:CBoolNegativeConverter x:Key="BoolNeg"/> </ResourceDictionary> </Application.Resources> </Application>
これでBoolNegがStaticResourceに登録されるので、GUIのXAMLでエラーが出なくなります。
後は、ONボタン、OFFボタンのクリックイベントハンドラを実装し、押されたボタンによって、ONボタンのIsEnabledを変更すればONボタンとOFFボタンのトグルができるようになります。
- OKボタンクリック -> IsEnabled = False
- OFFボタンクリック -> IsEnabled = True
今回はここまでです。
このbool型の反転バインドができるだけで、世界が変わります。