Enum と RadioButton をバインドする
よくある感じのネタで恐縮ですがー。
RadioButton といえばやはり Enum。コンバータを使用して、こんな感じでバインドします。
<!-- Window1.xaml --> <Window x:Class="ConverterTest.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:ConverterTest" Title="RadioButton と Enum をバインドする"> <Window.Resources> <!-- コンバータ --> <local:EnumRadioConverter x:Key="enumRadioConverter"/> </Window.Resources> <StackPanel> <Button x:Name="ButtonTarget" Margin="5" >穴があったら入りたい…。</Button> <RadioButton IsChecked="{Binding ElementName=ButtonTarget, Path=Visibility, Converter={StaticResource enumRadioConverter}, ConverterParameter=Visible}" Margin="5" GroupName="ButtonVisibility">白日の下に曝す</RadioButton> <RadioButton IsChecked="{Binding ElementName=ButtonTarget, Path=Visibility, Converter={StaticResource enumRadioConverter}, ConverterParameter=Hidden}" Margin="5" GroupName="ButtonVisibility">隠してあげる</RadioButton> </StackPanel> </Window>
コンバータのソースです。
public class EnumRadioConverter : System.Windows.Data.IValueConverter { // Enum → bool public object Convert (object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { // バインドする列挙値の文字列表記がパラメータに渡されているか var paramString = parameter as string; if (paramString == null) { return System.Windows.DependencyProperty.UnsetValue; } // パラメータが Enum の値として正しいか if (!Enum.IsDefined (value.GetType (), paramString)) { return System.Windows.DependencyProperty.UnsetValue; } // パラメータを Enum に変換 var paramParsed = Enum.Parse (value.GetType (), paramString); // 値が一致すれば true を返す return (value.Equals (paramParsed)); } // bool → Enum public object ConvertBack (object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { // バインドする列挙値の文字列表記がパラメータに渡されているか var paramString = parameter as string; if (paramString == null) { return System.Windows.DependencyProperty.UnsetValue; } // チェックが入っているか (この評価は不要?) var isChecked = (bool) value; if (!isChecked) { return System.Windows.DependencyProperty.UnsetValue; } // 列挙型にパースして返す return Enum.Parse (targetType, paramString); } }
トラックバック
- このエントリーにトラックバック:
- http://frog.raindrop.jp/cgi-bin/mt/mt-tb.cgi/2203
コメント