我正在寻找一种方法来本地化在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本地化?或者是否有办法使用微软似乎正在使用的Visual Studio?
发布于 2008-12-11 13:37:57
这是我最终在一个单独的程序集中得到的解决方案(在我的例子中称为"Common“):
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event)]
public class DisplayNameLocalizedAttribute : DisplayNameAttribute
{
public DisplayNameLocalizedAttribute(Type resourceManagerProvider, string resourceKey)
: base(Utils.LookupResource(resourceManagerProvider, resourceKey))
{
}
}
使用查找资源的代码:
internal static string LookupResource(Type resourceManagerProvider, string resourceKey)
{
foreach (PropertyInfo staticProperty in resourceManagerProvider.GetProperties(BindingFlags.Static | BindingFlags.NonPublic))
{
if (staticProperty.PropertyType == typeof(System.Resources.ResourceManager))
{
System.Resources.ResourceManager resourceManager = (System.Resources.ResourceManager)staticProperty.GetValue(null, null);
return resourceManager.GetString(resourceKey);
}
}
return resourceKey; // Fallback with the key name
}
典型的用法是:
class Foo
{
[Common.DisplayNameLocalized(typeof(Resources.Resource), "CreationDateDisplayName"),
Common.DescriptionLocalized(typeof(Resources.Resource), "CreationDateDescription")]
public DateTime CreationDate
{
get;
set;
}
}
当我使用文本字符串作为资源键时,这是非常丑陋的。在那里使用常量意味着修改Resources.Designer.cs,这可能不是一个好主意。
结论:我对此并不满意,但我更不高兴的是微软不能提供任何有用的东西来完成这样一个普通的任务。
发布于 2010-10-07 05:47:32
在MVC4中有来自System.ComponentModel.DataAnnotations的Display attribute,它工作在.NET 3的PropertyGrid
上。
[Display(ResourceType = typeof(MyResources), Name = "UserName")]
public string UserName { get; set; }
这将在MyResources
.resx文件中查找名为UserName
的资源。
https://stackoverflow.com/questions/356464
复制相似问题