将单选按钮绑定到枚举属性

本文关键字:枚举 属性 绑定 单选按钮 | 更新日期: 2023-09-27 18:18:57

我想我已经遵循了这篇文章中给出的例子,但是当按钮改变时,我的属性并没有改变。我哪里做错了,有什么建议吗?

枚举和类 的c#代码
public enum SystemTypes
{
    TypeA,
    TypeB
}
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    SystemTypes systemType = SystemTypes.TypeA;
    public SystemTypes SystemType 
    {
        get { return systemType; }
        set { systemType = value; }
    }
}
public class EnumToBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value.Equals(parameter);
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value.Equals(true) ? parameter : Binding.DoNothing;
    }
}

xaml

        <Canvas>
            <Canvas.Resources>
                <local:EnumToBooleanConverter x:Key="EnumToBooleanConverter" />
            </Canvas.Resources>
            <RadioButton x:Name="TypeARadioButton" Content="TypeA" Canvas.Left="10" Canvas.Top="10" 
                         IsChecked="{Binding Path=SystemType, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static local:SystemTypes.TypeA}}" />
            <RadioButton x:Name="TypeBRadioButton" Content="TypeB" Canvas.Left="10" Canvas.Top="31"
                         IsChecked="{Binding Path=SystemType, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static local:SystemTypes.TypeB}}" />
        </Canvas>

将单选按钮绑定到枚举属性

您需要将Binding Mode设置为two - way,然后在Converter中实现方法ConvertBack负责将bool转换为SystemType,在SystemType的setter中包括

set { systemType = value; OnPropertyChanged(() => "SystemType");}

以填充其值已更改的属性。

OnPropertyChanged(() => "SystemType")

可以工作,如果你实现接口INotifyPropertyChanged。我不知道你是否设置了DataContext,如果你没有绑定就不工作了。为了纠正这个问题,在InitializeComponent()之后添加

this.DataContext = this;