DisplayNameAttribute的本地化

我正在寻找一种本地化PropertyGrid中显示的属性名称的方法。使用DisplayNameAttribute属性可以将该属性的名称“覆盖”。不幸的是,属性不能具有非常量表达式。因此,我不能使用强类型资源,例如:


class Foo

{

   [DisplayAttribute(Resources.MyPropertyNameLocalized)]  // do not compile

   string MyProperty {get; set;}

}

我环顾四周,发现一些建议可以从DisplayNameAttribute继承来使用资源。我最终会得到如下代码:


class Foo

{

   [MyLocalizedDisplayAttribute("MyPropertyNameLocalized")] // not strongly typed

   string MyProperty {get; set;}

}

但是,我失去了强类型资源的好处,这绝对不是一件好事。然后我遇到了DisplayNameResourceAttribute,这可能是我想要的。但这应该在Microsoft.VisualStudio.Modeling.Design命名空间中,而我找不到应该为该命名空间添加的引用。


有人知道是否有一种简便的方法可以很好地实现DisplayName本地化?或者是否可以使用Microsoft似乎在Visual Studio中使用的方式?


qq_笑_17
浏览 1121回答 3
3回答

呼如林

我们为许多属性执行此操作,以支持多种语言。我们对Microsoft采取了类似的方法,即它们覆盖其基本属性并传递资源名称而不是实际字符串。然后,该资源名称用于在DLL资源中执行查找,以返回实际的字符串。例如:class LocalizedDisplayNameAttribute : DisplayNameAttribute{    private readonly string resourceName;    public LocalizedDisplayNameAttribute(string resourceName)        : base()    {      this.resourceName = resourceName;    }    public override string DisplayName    {        get        {            return Resources.ResourceManager.GetString(this.resourceName);        }    }}在实际使用属性时,您可以更进一步,并在静态类中将资源名称指定为常量。这样,您将获得类似的声明。[LocalizedDisplayName(ResourceStrings.MyPropertyName)]public string MyProperty{  get  {    ...  }}更新ResourceStrings看起来像(注意,每个字符串将引用指定实际字符串的资源名称):public static class ResourceStrings{    public const string ForegroundColorDisplayName="ForegroundColorDisplayName";    public const string FontSizeDisplayName="FontSizeDisplayName";}

UYOU

.NET 4中有System.ComponentModel.DataAnnotations 的Display属性。它在MVC 3上有效PropertyGrid。[Display(ResourceType = typeof(MyResources), Name = "UserName")]public string UserName { get; set; }这将UserName在您的MyResources.resx文件中查找命名的资源。
打开App,查看更多内容
随时随地看视频慕课网APP