我正在处理的一个项目定义了一个只有两种状态的枚举。我正在使用切换按钮来切换属性值。
使用我编写的用于将枚举绑定(bind)到一组单选按钮的值转换器不起作用,因为由于 Binding.DoNothing
,它只能以一种方式更改值。
这是用于单选按钮的 bool 值转换器的枚举,它只在一个方向上改变值:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.Equals(parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.Equals(true) ? parameter : Binding.DoNothing;
}
作为解决方法,我专门针对我正在使用的枚举修改了它,如下所示,将 ConvertBack< 中的
方法Binding.DoNothing
替换为 MyEnum.Off
/
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.Equals(parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.Equals(true) ? parameter : MyEnum.Off;
}
是否有更好的方法来切换返回的枚举值以启用切换按钮将枚举切换到可跨不同枚举类型重用的关闭状态?
最佳答案
没有任何类型/空/等检查的最简单的如下:
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return System.Convert.ToBoolean(value);
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return Enum.ToObject(targetType, value);
}
System.Convert.ToBoolean
接受任何值 类型而不抛出异常。
您还可以进行一些额外的类型检查,例如 if (targetType.IsEnum)
,但这取决于您。
根据msdn:Enum.ToObject()
只接受 SByte、Int16、Int32、Int64、Byte、UInt16、UInt32 或 UInt64。
,但我怀疑它在内部使用 System.Convert
,因此也接受 bool 值。
关于c# - 使用值转换器将切换按钮绑定(bind)到枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35899342/