従来のWindowsFormのラジオボタンでは、現在どの値になっているか、すべてのラジオボタンをチェックする必要がありました。
WPFの場合には素敵なバインディングが備わっているので、もともと各コントロールに名前を付けるなんていう無粋なことはしません。
バインディングをべたな方法で考えると
<RadioButton IsChecked="{Binding Path=RadioA}" />
<RadioButton IsChecked="{Binding Path=RadioB}" />
このようにひとつひとつboolでバインドすることになります。
しかし、これではバインドした値のboolをすべて見て回ることになります。全くいけてません。
ということで、みんなはどうしているか調べてみたところ、
http://blogs.interknowlogy.com/johnbowen/archive/2007/06/21/20468.aspx
というのを発見
<RadioButton IsChecked="{Binding Path=GlobalState, Mode=TwoWay, Converter={StaticResource EnumMatchToBooleanConverter}, ConverterParameter=Off}" Content="Off" Margin="5"/> <RadioButton IsChecked="{Binding Path=GlobalState, Mode=TwoWay, Converter={StaticResource EnumMatchToBooleanConverter}, ConverterParameter=Ready}" Content="Ready" Margin="5"/>
Enumに直接バインドしています。
コンバータパラメータを供給することにより、どの値を意味するかを決定しているわけです。
で、このコンバータのソースはなかったんですが、理屈は簡単なので実装します。
public class EnumBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string ParameterString = parameter as string;
if (ParameterString == null)
{
return DependencyProperty.UnsetValue;
}
if (Enum.IsDefined(value.GetType(), value) == false)
{
return DependencyProperty.UnsetValue;
}
object paramvalue = Enum.Parse(value.GetType(), ParameterString);
if (paramvalue == value)
{
return true;
}
else
{
return false;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
string ParameterString = parameter as string;
if (ParameterString == null)
{
return DependencyProperty.UnsetValue;
}
return Enum.Parse(targetType, ParameterString);
}
}
このコンバータは普遍的なコンバータです。
どの局面でも使えます。是非使ってください。