namespace HKW.HKWUtils; /// /// 可观察的枚举标签模型 /// /// 枚举类型 public class ObservableEnumFlags : ObservableClass> where T : Enum { private T _EnumValue; public T EnumValue { get => _EnumValue; set => SetProperty(ref _EnumValue, value); } /// /// 添加枚举命令 /// public ObservableCommand AddCommand { get; } = new(); /// /// 删除枚举命令 /// public ObservableCommand RemoveCommand { get; } = new(); /// /// 枚举类型 /// public Type EnumType = typeof(T); /// /// 枚举基类 /// public Type UnderlyingType { get; } = Enum.GetUnderlyingType(typeof(T)); public ObservableEnumFlags() { if (Attribute.IsDefined(EnumType, typeof(FlagsAttribute)) is false) throw new Exception($"此枚举类型未使用特性 [{nameof(FlagsAttribute)}]"); AddCommand.ExecuteCommand += AddCommand_Execute; RemoveCommand.ExecuteCommand += RemoveCommand_Execute; } public ObservableEnumFlags(T value) : this() { EnumValue = value; } private void AddCommand_Execute(T v) { if (UnderlyingType == typeof(int)) { EnumValue = (T) Enum.Parse(EnumType, (Convert.ToInt32(EnumValue) | Convert.ToInt32(v)).ToString()); } else throw new NotImplementedException($"Value type: {UnderlyingType}"); } private void RemoveCommand_Execute(T v) { if (UnderlyingType == typeof(int)) { EnumValue = (T) Enum.Parse(EnumType, (Convert.ToInt32(EnumValue) & ~Convert.ToInt32(v)).ToString()); } else throw new NotImplementedException($"Value type: {UnderlyingType}"); } }