【发布时间】:2020-04-10 00:51:03
【问题描述】:
我可以| 和& 等enum,但不能Enum。为什么是这样?有没有办法解决?我正在尝试为 WPF 编写一个 Enum 标志转换器。
public class EnumFlagConverter : IValueConverter
{
public Enum CurrentValue;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var theEnum = value as Enum;
CurrentValue = theEnum;
return theEnum.HasFlag(parameter as Enum);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
Enum CurrentValue;
var theEnum = parameter as Enum;
if (CurrentValue.HasFlag(theEnum)) //this line is allowed
return CurrentValue &= ~theEnum; //~theEnum not allowed, neither is the &=
else
return CurrentValue |= theEnum; // |= cannot be applied to Enum and Enum
}
}
【问题讨论】:
-
您能否将类型指定为
int,并希望隐式转换为Enum有效? -
你会接受“因为 Enum 是一个没有定义这些操作的类”我想我很难理解这种混淆。这和你不能做 string foo |= "bar" 的原因是一样的
-
了解“Enum”(实际上是 System.Enum)是一种类型,而“enum”是用于声明类型的关键字,这也可能会有所帮助。
-
当转换器用于多个绑定时,您将如何跟踪绑定源的“当前值”? IMO 反向转换根本没有意义。您至少应该从
ConvertBack方法中删除本地CurrentValue变量。 -
@Clemens 我不必为多个绑定使用同一个转换器,如果这是我必须处理的限制的话。