Loading

WPF中RadioButton的数据绑定

一、问题描述

RadioButton一般用于单选的时候,也就是从一组值中选择一个值。RadioButton有一个IsChecked属性用于表示是否选中。

比如性别有“男”、“女”、“未知”三种取值,对应三个RadioButton按钮。

二、数据声明

枚举定义如下所示:

 public enum Sex
    {
        Unknown=0,
        Max=1,
        Woman=2,
    }

ViewModel如下所示:

 public class NotifyPropertyChanged : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void SetProperty<T>(ref T prop, T value, [CallerMemberName] string propertyName = null)
        {
            if (EqualityComparer<T>.Default.Equals(prop, value) == false)
            {
                prop = value;
                OnPropertyChanged(propertyName);
            }
        }

        public virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
 public class MainWindowVM:NotifyPropertyChanged
    {
        private Sex _sex;

        public Sex Sex
        {
            get => _sex;
            set => SetProperty( ref _sex,  value);
        }
    }

由于RadioButton的IsChecked的属性值为bool,而Sex为枚举类型,因此需要类型转换:

 public class SexToIsCheckedCvt : IValueConverter
    {
        public static SexToIsCheckedCvt Cvt = new SexToIsCheckedCvt();
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value?.ToString() == parameter?.ToString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (bool.TryParse(value?.ToString(), out var isChecked) && 
                Enum.TryParse<Sex>(parameter?.ToString(), out var param))
            {
                if (isChecked)
                {
                    return param;
                }
            }
            return value;
        }
    }

三、数据绑定

将ViewModel的Sex属性和RadioButton的IsChecked属性绑定:

            <RadioButton GroupName="sex" IsChecked="{Binding Sex,Converter={x:Static mvvm:SexToIsCheckedCvt.Cvt},ConverterParameter={x:Static mvvm:Sex.Unknown}}">未知</RadioButton>
            <RadioButton GroupName="sex" IsChecked="{Binding Sex,Converter={x:Static mvvm:SexToIsCheckedCvt.Cvt},ConverterParameter={x:Static mvvm:Sex.Max}}">男</RadioButton>
            <RadioButton GroupName="sex" IsChecked="{Binding Sex,Converter={x:Static mvvm:SexToIsCheckedCvt.Cvt},ConverterParameter={x:Static mvvm:Sex.Woman}}">女</RadioButton>
posted @ 2021-07-07 23:53  Dwaynerbing  阅读(3299)  评论(0编辑  收藏  举报