如何本地化类显示名称

时间:2015-02-12 20:10:08

标签: c# localization data-annotations

如何使用资源文件本地化该类的DisplayName。 显示属性不适用于类,DisplayName属性不支持本地化。

[MetadataTypeAttribute(typeof(ServiceType.ServiceTypeMetadata))]
// Compile Error: Attribute 'Display' is not valid on this declaration type. It is only valid on 'method, property, indexer, field, param' declarations.
// [Display(ResourceType = typeof(Resources.DisplayNames), Name = "ServiceType")] 
[System.ComponentModel.DisplayName("Service Type")]
public partial class ServiceType : ILookupEntity<EdmBilingualStringVarCharSingleLine>, ISelectListEntity, IUpdateableEntity
{
    #region Metadata
    internal sealed class ServiceTypeMetadata
    {
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [Display(ResourceType = typeof(Resources.DisplayNames), Name = "InactiveDate")]
        public DateTime? InactiveDate { get; set; }
        [Display(ResourceType = typeof(Resources.DisplayNames), Name = "ModifiedBy")]
        [Required]
        public string ModifiedBy { get; set; }
        [Display(ResourceType = typeof(Resources.DisplayNames), Name = "ModifiedDate")]
        [Required]
        public System.DateTime ModifiedDate { get; set; }

    }
    #endregion

    // ... the rest of the class ....
}

1 个答案:

答案 0 :(得分:0)

解决方案是创建自己的“显示名称”属性。下面的工作对我来说可以通过传递资源文件名来更通用,在我的例子中我简单地硬编码。

using System.ComponentModel;
using System.Resources;


namespace SCC.Case.Entities
{
    /// <summary>
    /// Provides a class attribute that lets you specify the localizable string for the entity class
    /// </summary>
    class DisplayNameForClassAttribute : DisplayNameAttribute
    {
        public string Name { get; set; }
        public override string DisplayName
        {
            get
            {
                ResourceManager resourceManager = new ResourceManager("SCC.Case.Entities.DisplayNames", typeof(DisplayNameForClassAttribute).Assembly);
                return resourceManager.GetString(this.Name);
            }
        }
    }
}