使用本地化枚举作为DataSource

时间:2011-11-18 21:28:51

标签: c# .net winforms localization enums

我的应用中有很多枚举。其中大多数都用在这样的组合上:

Enum.GetValues(typeof(TipoControlador))

现在我想将它们本地化为:Localizing enum descriptions attributes

我该如何组合它们?我的第一个想法是使用扩展方法覆盖ToString方法,但这是不可能的=(

3 个答案:

答案 0 :(得分:1)

使用其他文章作为基础,您可以创建如下的扩展方法:

public static class LocalizedEnumExtensions
{
    private static ResourceManager _resources = new ResourceManager("MyClass.myResources",
        System.Reflection.Assembly.GetExecutingAssembly());

    public static IEnumerable<string> GetLocalizedNames(this IEnumerable enumValues)
    {
        foreach(var e in enumValues)
        {
            string localizedDescription = _resources.GetString(String.Format("{0}.{1}", e.GetType(), e));
            if(String.IsNullOrEmpty(localizedDescription))
            {
                yield return e.ToString();
            }
            else
            {
                yield return localizedDescription;
            }
        }
    }
}

您可以这样使用它:

Enum.GetValues(typeof(TipoControlador)).GetLocalizedNames();

从技术上讲,此扩展方法将接受任何数组,并且您不能将其限制为仅在枚举上工作,但如果您觉得它很重要,您可以在扩展方法中添加额外的验证:

if(!e.GetType().IsEnum) throw new InvalidOperationException(String.Format("{0} is not a valid Enum!", e.GetType()));

答案 1 :(得分:1)

这里有2个问题,第一个是如何本地化由Localizing enum descriptions attributes解决的枚举。

第二个是如何在使用枚举值时显示本地化名称。这可以通过创建一个简单的包装器对象来解决,例如:

public sealed class NamedItem
{
    private readonly string name;
    private readonly object value;

    public NamedItem (string name, object value)
    {
        this.name = name;
        this.value = value;
    }

    public string Name { get { return name; } }
    public object Value { get { return value; } }

    public override string ToString ()
    {
        return name;
    }
}

这为任何下拉框提供了一个通用的可重用类,您可能希望为项显示与项本身提供的名称不同的名称(例如枚举,整数等)。

完成此课程后,您可以将下拉列表的DisplayMember设置为Name,将ValueMember设置为Value。这意味着dropdown.SelectedValue仍将返回您的枚举。

答案 2 :(得分:0)

我知道这个问题已经过时了,但这可能对某些人有所帮助。 您可以只处理ComboBox控件的Format事件(http://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.format.aspx),并在其中添加文本逻辑。

    private void ComboBoxFormat(object sender, ListControlConvertEventArgs e)
    {
        e.Value = GetDescription(e.Value);
    }

    public static string GetDescription(object item)
    {
        string desc = null;

        Type type = item.GetType();
        MemberInfo[] memInfo = type.GetMember(item.ToString());
        if (memInfo != null && memInfo.Length > 0)
        {
            object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attrs != null && attrs.Length > 0)
            {
                desc = (attrs[0] as DescriptionAttribute).Description;
            }
        }

        if (desc == null) // Description not found
        {
            desc = item.ToString();
        }

        return desc;
    }

有了这个,ComboBox控件仍然保存枚举值而不是字符串。