这是我用来生成从枚举 int 值到其文本值的翻译的自定义转换器。
WPF Xaml gridviewdatacolumn 片段
... DataMemberBinding="{Binding Path=ProductTypeId, Converter={StaticResource IntEnumValueToDisplayNameConverter1}, ConverterParameter=Solution1.SomePath.SomeOtherPath\, Solution1\.SomePath\, Version\=1\.0\.0\.0\, Culture\=neutral\, PublicKeyToken\=null}"
转换器代码示例:
namespace Solution1.SomePath.Converters
{
using System;
using System.Globalization;
using System.Windows.Data;
internal class IntEnumValueToDisplayNameConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
if (value == null || parameter == null)
return null;
var type = GetTypeFromParameter(parameter);
if (type == null)
return null;
var enumValue = Enum.Parse(type, value.ToString(), true);
if (enumValue == null)
return null;
return enumValue.ToString();
}
catch (Exception)
{
return null;
}
}
private static Type GetTypeFromParameter(object parameter)
{
if (parameter == null)
return null;
Type type;
if (parameter is Type)
{
type = parameter as Type;
if (type == null || !type.IsEnum)
return null;
}
else if (parameter is string)
{
// Must be fully qualified assembly name to work
// Example: Solution1.SomePath.SomeOtherPath, Solution1.SomePath, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
var typeName = parameter as string;
if (typeName.IsEmpty())
return null;
type = Type.GetType(typeName);
if (type == null || !type.IsEnum)
return null;
}
else
return null;
return type;
}
}
}