是否可以为EnumConverter始终使用而不是默认值的枚举类型编写自定义EnumConverter?
我希望在我的 XAML 代码中随处使用此转换器,而无需指定要使用的转换器(如果可能)
我找到了如何做到这一点 :-) 这会将这种类型的所有枚举转换为选定的字符串。
首先,我必须向我的枚举添加一个 TypeConverter 属性:
using System.ComponentModel;
namespace WpfTestTypeConverter
{
[TypeConverter(typeof(DeviceTypeConverter))]
public enum DeviceType
{
Computer,
Car,
Bike,
Boat,
TV
}
}
Run Code Online (Sandbox Code Playgroud)
而且我还必须基于 EnumConverter 类编写一个转换器
using System;
using System.ComponentModel;
using System.Globalization;
namespace WpfTestTypeConverter
{
public class DeviceTypeConverter : EnumConverter
{
public DeviceTypeConverter(Type type) : base(type)
{
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return (destinationType == typeof(string));
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (value is DeviceType)
{
DeviceType x = (DeviceType)value;
switch (x)
{
case DeviceType.Computer:
return "This is a computer";
case DeviceType.Car:
return "A big car";
case DeviceType.Bike:
return "My red bike";
case DeviceType.Boat:
return "Boat is a goat";
case DeviceType.TV:
return "Television";
default:
throw new NotImplementedException("{x} is not translated. Add it!!!");
}
}
return base.ConvertFrom(context, culture, value);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这有效。有人对此解决方案有任何意见吗?