c# - 将单选按钮绑定(bind)到枚举属性

标签 c# wpf xaml enums radio-button

我想我已经遵循了 post 中给出的示例但是当按钮改变时我的属性没有改变。关于我哪里出错的任何建议?

枚举和类的 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为TwoWay,然后在Converter中实现方法ConvertBack负责将bool转换为SystemTypes,在SystemType的settter中包含

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

为了填充其值已更改的属性。

OnPropertyChanged(() => "SystemType")

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

this.DataContext = this;

关于c# - 将单选按钮绑定(bind)到枚举属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25414802/

相关文章:

c# - 两个应用程序实例之间的简单通信

c# - 从 DataGrid 中自动删除新行

c# - System.WIndows.Application 静态成员是线程安全的吗?

c# - 如何创建可以显示不同类型对象的 C# WPF DataGrid?

c# - 定义 UserControl 属性并在 Windows Phone 中绑定(bind)它们

c# - 如何根据 C# 中字符串中元素的出现对数组进行排序?

c# - 如何在没有 Controller 的情况下手动提供 .cshtml 文件?

xaml - Xamarin MVVM不透明度转换器?

wpf - 在wpf mvvm中成功保存后如何自动更新 ListView 中的选定行

C# 将指向结构(包含不可直接传送类型)的指针传递给非托管 C++ DLL