从资源DisplayName特性? [英] DisplayName attribute from Resources?

查看:268
本文介绍了从资源DisplayName特性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个本地化的应用程序,我想知道是否有可能有从资源设置一定的模型属性显示名称。

I have a localized application, and I am wondering if it is possible to have the DisplayName for a certain model property set from a Resource.

我想要做这样的事情:

public class MyModel {
  [Required]
  [DisplayName(Resources.Resources.labelForName)]
  public string name{ get; set; }
}

但我不能给它,因为编译器说:一个属性参数必须是常量前pression,属性参数类型的typeof前pression或数组创建前pression (

But I can't to it, as the compiler says: "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type" :(

是否有任何变通办法?我手动输出的标签,但我需要这些验证器的输出!

Are there any workarounds? I am outputting labels manually, but I need these for the validator output!

推荐答案

如何写一个自定义属性:

How about writing a custom attribute:

public class LocalizedDisplayNameAttribute: DisplayNameAttribute
{
    public LocalizedDisplayNameAttribute(string resourceId) 
        : base(GetMessageFromResource(resourceId))
    { }

    private static string GetMessageFromResource(string resourceId)
    {
        // TODO: Return the string from the resource file
    }
}

它可以用来这样的:

which could be used like this:

public class MyModel 
{
    [Required]
    [LocalizedDisplayName("labelForName")]
    public string Name { get; set; }
}

这篇关于从资源DisplayName特性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆