2010-08-26 92 views
10

是否有一個屬性允許您爲類中的屬性指定用戶友好的名稱?是否有.NET屬性用於指定屬性的「顯示名稱」?

例如,說我有下面的類:

public class Position 
{ 
    public string EmployeeName { get; set; } 
    public ContactInfo EmployeeContactInfo { get; set; } 
} 

我想指定爲EmployeeName性的顯示名稱是「員工姓名」和顯示名稱爲EmployeeContactInfo屬性爲「員工聯繫信息「。

這足以寫我自己的屬性類,它可以讓我做到這一點很簡單:

[PropertyDisplayInfo(DisplayName = "Employee Name")] 
public string EmployeeName { get; set; } 

但就是這樣的已經包含在.NET?

回答

13
+11

作爲.NET 4中,對於這更好的屬性,System.ComponentModel.DataAnnotations.DisplayAttribute – 2010-08-26 23:41:32

+5

對於其他人尋找這樣做的好處答案,.NET 4.0中的Windows窗體DataGridView或PropertyGrid控件不支持System.ComponentModel.DataAnnotations.DisplayAttribute,因此您又回到了使用System.ComponentModel.DisplayNameAttribute(並且編寫自己的派生類,如果您想要支持本地化)。 – MCattle 2013-03-11 15:34:32

11

System.ComponentModel.DataAnnotations.DisplayAttributeDisplayNameAttribute一個更好的選擇,這實際上是用於物業電網使用。現在.NET世界中的更多組件將採用並使用DisplayAttribute。它還具有諸如OrderGroupName,ShortName以及當自動生成完成時(AutoGenerateField)是否顯示屬性。

DisplayAttribute也是資源友好的,使其成爲本地化的一個不錯的選擇。

0

將每個屬性聲明之前,以下屬性:

//[DisplayName("Your desired human readable field caption ")] 
    [DisplayName("ID")] 
    public int id { 
     get {return _id;} 
     set { SetField(ref _id, value, "id"); } 
    } 
相關問題