【问题标题】:Binding radio button to enum property将单选按钮绑定到枚举属性
【发布时间】:2014-10-14 09:44:58
【问题描述】:

我想我已经遵循了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>

【问题讨论】:

  • 您没有为窗口设置 DataContext,因此它找不到要绑定的 SystemType 属性。

标签: c# wpf xaml enums radio-button


【解决方案1】:

你需要设置Binding Mode为TwoWay,然后在Converter中实现方法ConvertBack负责将bool转换为SystemTypes,在SystemType的settter中包含

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

为了填充属性,它的值被改变了。

OnPropertyChanged(() => "SystemType")

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

this.DataContext = this;

【讨论】:

  • 抱歉忘记添加转换器代码。我也编辑了问题以显示该课程,我也尝试了两种方法。您指定的代码不会编译,因为 lambda 表达式不是委托类型,但我认为这并不重要,因为永远不会调用 setter。
猜你喜欢
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 2012-09-22
  • 1970-01-01
  • 2012-05-18
  • 2013-08-19
  • 1970-01-01
  • 2014-02-03
相关资源
最近更新 更多