Skip to main content
 首页 » 编程设计

c#之DisplayAttribute 未在模型中本地化其属性

2024年02月20日11luoye11

我在我的 WPF 应用程序中使用 MVVM 模式,并将具有本地化功能的 DisplayAttribute 应用于我的模型属性:

class MyModel 
{ 
    [Display( 
        ResourceType = typeof(Resources.Strings), 
        Name = "MyPropertyName", 
        Description = "MyPropertyDescription")] 
    public double MyProperty { get; set; } 
} 

我想显示模型属性的本地化属性。必要的资源文件位于适当的位置,必要的文化设置。我还将构建操作设置为嵌入式资源,并将自定义工具设置为 PublicResXFileCodeGenerator - 根据 DisplayAttribute 的要求。但是 DisplayAttribute 为其 Name 参数返回“MyPropertyName”而不是本地化字符串。

我使用 DisplayProperty 的场景如下所示。为了显示模型属性的属性属性,我使用了一个带有辅助类的转换器,如下所示:

namespace MyProject.Converters 
{ 
    // helper class 
    public class MetadataParameters 
    { 
        public Type ModelType { get; set; } 
        public string ModelProperty { get; set; } 
        public Type AttributeType { get; set; } 
        public string AttributeProperty { get; set; } 
    } 
 
    public class MetadataConverter : IValueConverter 
    { 
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
        { 
            var mp = parameter as MetadataParameters; 
            var modelPropertyInfo = mp.ModelType.GetProperty(mp.ModelProperty); 
            var attribute = modelPropertyInfo 
                .GetCustomAttributes(true) 
                .Cast<Attribute>() 
                .FirstOrDefault(memberInfo => memberInfo.GetType() == mp.AttributeType); 
            var attributeProperty = attribute.GetType().GetProperty(mp.AttributeProperty); 
 
            return attributeProperty.GetValue(attribute, null); 
        } 
    } 
} 

XAML 资源:

xmlns:converters="clr-namespace:MyProject.Converters" 
<converters:MetadataConverter x:Key="metadataConverter" /> 

XAML:

xmlns:converters="clr-namespace:MyProject.Converters" 
xmlns:DataAnnotations="clr-namespace:System.ComponentModel.DataAnnotations;assembly=System.ComponentModel.DataAnnotations" 
xmlns:Models="clr-namespace:MyProject.Models" 
 
<TextBlock  
    <TextBlock.Text> 
        <Binding 
            Mode="OneWay" 
            Converter="{StaticResource metadataConverter}"> 
            <Binding.ConverterParameter> 
                <converters:MetadataParameters 
                    ModelType="{x:Type Models:Model}" 
                    ModelProperty="ModelProperty" 
                    AttributeType="{x:Type DataAnnotations:DisplayAttribute}" 
                    AttributeProperty="Name" />                             
            </Binding.ConverterParameter> 
        </Binding> 
    </TextBlock.Text> 
</TextBlock> 

我编写了自己的简单属性,它返回本地化的字符串,而不仅仅是属性名称的值(如 DisplayAttribute 所做的那样):

public class LocalizedDisplayAttribute : Attribute 
{ 
    private readonly string name; 
 
    public virtual string Name 
    { 
        get 
        { 
            var rm = new System.Resources.ResourceManager(typeof(Resources.Strings)); 
            return rm.GetString(this.name); 
        } 
    } 
 
    public LocalizedDisplayAttribute(string name) 
        : base() 
    { 
        this.name = name; 
    } 
} 
 
 
class MyModel 
{ 
    [LocalizedDisplay("MyPropertyName")] 
    public double MyProperty { get; set; } 
} 

那么为什么 DisplayAttribute 不本地化它的属性呢? MSDN 说这个属性是为本地化而设计的。在我的 ASP.NET MVC 项目中,DisplayAttribute 工作正常。

请您参考如下方法:

DisplayAttribute 上有 Get 方法和您需要调用的其他一些方法,它们将为您提供您正在寻找的本地化字符串。您在这里所做的是获取 DisplayAttribute.Name 属性的值,即“MyPropertyName”。

如果您调用 DisplayAttribute.GetName(),它将查找由 ResourceType 属性指定的资源类,然后它将使用 Name 属性来反射(reflect)资源类型上的属性。

我更改了您的代码,假设您请求的 AttributeProperty 将获得一个 GetXXX() 方法。

public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
{ 
  var mp = parameter as MetadataParameters; 
  var modelPropertyInfo = mp.ModelType.GetProperty(mp.ModelProperty); 
  var attribute = modelPropertyInfo 
      .GetCustomAttributes(true) 
      .Cast<Attribute>() 
      .FirstOrDefault(memberInfo => memberInfo.GetType() == mp.AttributeType); 
 
  // We have to call the GetXXX methods on the attribute to get a localised result. 
  //return ((DisplayAttribute)attribute).GetName(); 
  var result = attribute 
    .GetType() 
    .InvokeMember( 
      "Get" + mp.AttributeProperty, 
      BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, 
      null, 
      attribute, 
      new object[0]);  
  return result; 
}