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