在WPF中将单选按钮组绑定到属性
在WPF中将单选按钮组绑定到属性
让我们想象我有:
然后在我的数据源类中有:
public bool RadioButton1IsChecked { get; set; } public bool RadioButton2IsChecked { get; set; } public enum RadioButtons { RadioButton1, RadioButton2, None } public RadioButtons SelectedRadioButton { get { if (this.RadioButtonIsChecked) return RadioButtons.RadioButton1; else if (this.RadioButtonIsChecked) return RadioButtons.RadioButton2; else return RadioButtons.None; } }
我能否直接将我的单选按钮绑定到SelectedRadioButton
属性?我只需要RadioButton1IsChecked
和RadioButton2IsChecked
属性来计算所选的单选按钮。
admin 更改状态以发布 2023年5月25日
\n
public enum RadioButtons { RadioButton1, RadioButton2, None } public RadioButtons SelectedRadioButton {get;set;} public class EnumBooleanConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var 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); return paramvalue.Equals(value); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { var ParameterString = parameter as string; var valueAsBool = (bool) value; if (ParameterString == null || !valueAsBool) { try { return Enum.Parse(targetType, "0"); } catch (Exception) { return DependencyProperty.UnsetValue; } } return Enum.Parse(targetType, ParameterString); } }
声明一个类似于以下枚举的枚举类型:
enum RadioOptions {Option1, Option2}
XAML:
转换器类:
public class EnumBooleanConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value.Equals(parameter); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return ((bool)value) ? parameter : Binding.DoNothing; } }