中の技術日誌ブログ

C#とC++/CLIと
VBと.NETとWindowsで戯れる
 

目次

Blog 利用状況

ニュース

自己紹介

大阪でソフトウェアエンジニアをやっています。
お仕事大募集中です。
記事執筆とか、助言依頼とかでも何でもどうぞ(*^_^*)
似顔絵 MSMVPロゴ
MSMVP Visual C# Since 2004/04-2011/03

記事カテゴリ

書庫

日記カテゴリ

00-整理

01-MSMVP

WPFのラジオボタンとEnumの素敵な関係

従来の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);
    }
}


このコンバータは普遍的なコンバータです。

どの局面でも使えます。是非使ってください。

投稿日時 : 2007年9月16日 19:14

コメントを追加

# re: WPFのラジオボタンとEnumの素敵な関係 2007/09/18 13:54 中博俊

if(paramvalue==value)

if((int)paramvalue == (int)value)
に変更してください。バグってます。

# re: WPFのラジオボタンとEnumの素敵な関係 2009/09/01 19:52 mohno

たまたま検索してたどりつきました。
(今は?)ラジオボタンごとに GroupName を変えておかないと、うまく動作しないようですね。
http://wpftutorial.net/RadioButton.html

タイトル  
名前  
URL
コメント