我有以下枚举:
[Flags]
public enum SubscriberLevel {
BRONZE = 1,
SILVER1 = 2,
SILVER2 = 4,
SILVER = SubscriberLevel.SILVER1 | SubscriberLevel.SILVER2,
GOLD1 = 8,
GOLD2 = 16,
GOLD3 = 32,
GOLD = SubscriberLevel.GOLD1 | SubscriberLevel.GOLD2 | SubscriberLevel.GOLD3,
DIAMOND1 = 64,
DIAMOND2 = 128,
DIAMOND3 = 256,
DIAMOND = SubscriberLevel.DIAMOND1 | SubscriberLevel.DIAMOND2 | SubscriberLevel.DIAMOND3,
ALL = SubscriberLevel.BRONZE | SubscriberLevel.SILVER | SubscriberLevel.GOLD | SubscriberLevel.DIAMOND
}
我正在开发一个控件,它应该允许用户通过一系列复选框来指定此枚举中的一个、多个或所有标志。
在控件中,我有一个枚举成员和一个公开枚举的属性。控件本身继承了INotifyPropertyChanged方法,并且当值被设置时,属性的Setter正确地调用了OnPropertyChanged事件处理程序。
我甚至看到了控件内部某些类似功能的东西,但我没有看到它正常工作:
假设用户取消选中了“全部”选项;我希望每个复选框都反映这一点,并被清除,但我没有看到这种情况发生。
目前,我认为我的问题是我将这些复选框的Checked状态绑定到了枚举本身,而我需要做的是将枚举绑定到这些选中框,并且每个复选框代表枚举集合中的一个特定标志。
我已经注意到,在调试控件时,当我取消选中复选框时,值并没有被设置。为什么会这样?
我知道我需要使用转换器来完成这个操作,但现在,我该如何在XAML方面完成这个操作?将控件的DataContext定义为控件本身,然后将枚举标志与它们各自的复选框联系起来?
这是其中一个复选框的示例:
<CheckBox
x:Name="chkAll" Grid.Row="1" VerticalContentAlignment="Center" VerticalAlignment="Center"
IsChecked="{Binding Path=SubLevel, Converter={StaticResource ETBC},
ConverterParameter={x:Static Enums:SubscriberLevel.ALL}, Mode=TwoWay}"/>
这是转换器:
public class EnumToBoolConverter : IValueConverter {
public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture ) {
return ( ( Enum )value ).HasFlag( ( Enum )parameter );
}
public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture ) {
return value.Equals( true ) ? parameter : Binding.DoNothing;
}
}
这是该控件的代码(当前状态):
public partial class UCSubscriptionLevels : UserControl, INotifyPropertyChanged {
private SubscriberLevel _SubLevel = SubscriberLevel.ALL;
public event PropertyChangedEventHandler PropertyChanged;
public UCSubscriptionLevels( ) { InitializeComponent( ); }
/// <summary>
/// Get or Set Subscriber Levels to Build.
/// </summary>
public SubscriberLevel SubLevel {
get { return this._SubLevel; }
set {
this._SubLevel = value;
if ( this.PropertyChanged != null )
this.PropertyChanged( this, new PropertyChangedEventArgs( "SubLevel" ) );
}
}
}
编辑
已经有一段时间了,我忘记了依赖属性,所以我选择在控件上实现依赖属性而不是属性成员。但是行为仍然不稳定。以下是控件中该属性的新代码:
public static readonly DependencyProperty SubscriberLevelProperty =
DependencyProperty.Register( "SubLevel", typeof( SubscriberLevel ),
typeof( UCSubscriptionLevels ), new PropertyMetadata( SubscriberLevel.ALL ) );
.
.
.
/// <summary>
/// Get or Set Subscriber Levels to Build.
/// </summary>
public SubscriberLevel SubLevel {
get { return ( SubscriberLevel )this.GetValue( UCSubscriptionLevels.SubscriberLevelProperty ); }
set { this.SetValue( UCSubscriptionLevels.SubscriberLevelProperty, value ); }
}
然而,它仍然没有正常运作...
此外,我不得不改变枚举(从Bronze = 0 改为 Bronze = 1等)。