[英]Binding radio button to enum property
我想我已經遵循了本給出的例子后 ,但是當按鈕被改變我的屬性沒有改變。 關於我哪里出了錯的任何建議?
枚舉和類的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實施方法中將負責將bool轉換為SystemTypes的ConvertBack,在SystemType的settter中包括
set { systemType = value; OnPropertyChanged(() => "SystemType");}
為了填充屬性,其值已更改。
OnPropertyChanged(() => "SystemType")
如果實現接口INotifyPropertyChanged,則可以正常工作。 我無法確定是否設置DataContext,如果未綁定則無法正常工作。 為了糾正這個問題,在InitializeComponent()之后添加
this.DataContext = this;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.