LoginSignup
22
14

More than 5 years have passed since last update.

WPFでRadioButtonをBindingして使いたい!

Last updated at Posted at 2017-12-19

何かとめんどくさいWPFでRadioButtonを使うとき。Bindingするとなると何かとつらい。
いちいち使うときに自分のコードを見直して作っているので、すぐ見れるようにメモとして残しておきます。
今回はサンプルとして、簡易モードと詳細モードを分けるようなRadioButtonを作ります。

手順

  1. まずEnumを作ります。選択肢が分かりやすいようにします。
Enum.cs
public enum mode
{
    Simple,
    Detail
}
  1. ModelとViewModelに値を保持する為のプロパティを作成します。PropertyChangedを実装するなどは、MVVMで開発してきた方ならばおなじみだと思うのでここでは省略します。

  2. RadioButtonの値を取る為に必要なConverterを作成します。コードは以下のような感じになります。

BoolToEnumConverter.cs
public class BoolToEnumConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {

            var ParameterString = parameter as string;
            if (ParameterString == null)
            {
                return System.Windows.DependencyProperty.UnsetValue;
            }

            if (Enum.IsDefined(value.GetType(), value) == false)
            {
                return System.Windows.DependencyProperty.UnsetValue;
            }

            object paramvalue = Enum.Parse(value.GetType(), ParameterString);

            return (int)paramvalue == (int)value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var ParameterString = parameter as string;
            return ParameterString == null ? System.Windows.DependencyProperty.UnsetValue : Enum.Parse(targetType, ParameterString);
        }
    }

Bool値とEnumを変換するコンバーターです。
つまり、RadioButtonのTrueが入っていたところを探し、それをEnumに変換することで、
どのRadioButtonにチェックが入っているのかを判定します。

  1. ViewにRadioButtonを作ります。
View.xaml
<!--Resources内にコンバーターの使用を宣言する。-->
<converter:BoolToEnumConverter x:Key="Enum" />

<!--RadioButtonを設置。GroupNameはすべて別にする。バインド先はグループ単位で同じにする。-->
<RadioButton Margin="0,5,0,0" GroupName="RubySimple" Content="簡易"
IsChecked="{Binding RadioButtonValue, Converter={StaticResource Enum}, Mode=TwoWay, ConverterParameter=Simple}" />

<RadioButton Margin="0,0,0,0" GroupName="RubyDetail" Content="詳細"
IsChecked="{Binding RadioButtonValue, Converter={StaticResource Enum}, Mode=TwoWay, ConverterParameter=Detail}" />

これでOKです。バインドしたプロパティの中にどのEnumが入っているかを判定することで、どのRadioButtonにチェックが入っているかを調べることができます。

22
14
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
14