我需要動態地(從數據庫)爲屬性加載DisplayName
。例如這樣的事情:將非常量表達式設置爲DisplayName
[DisplayName(getDescriptionForLanguage("test"))]
public string test{ get; set; }
但這只是可以加載一個DisplayName
動態,唯一不變的是允許的。 是否有某種方法可以將DisplayName
作爲方法的結果而不是從Resourcefile或常量中獲取?
我需要動態地(從數據庫)爲屬性加載DisplayName
。例如這樣的事情:將非常量表達式設置爲DisplayName
[DisplayName(getDescriptionForLanguage("test"))]
public string test{ get; set; }
但這只是可以加載一個DisplayName
動態,唯一不變的是允許的。 是否有某種方法可以將DisplayName
作爲方法的結果而不是從Resourcefile或常量中獲取?
可以調用返回非常量字符串的方法。
你必須創建一個新的Attributclass,例如像這樣:
class DisplayNameLanguage : DisplayNameAttribute
{
private readonly string resourceName;
public DisplayNameLanguage(string resourceName)
: base()
{
this.resourceName = resourceName;
}
public override string DisplayName
{
get
{
return getDescriptionForLanguage(resourceName);
}
}
}
現在,你必須創建模型的部分子類。在那裏你可以使用新的屬性獲得你的方法描述getDescriptionForLanguage
:
[MetadataType(typeof(TestMD))]
public partial class Test { }
public partial class TestMD
{
[DisplayNameLanguage("Test")]
public string Prop1 { get; set; }
}
沒有辦法改變這種行爲。傳遞給屬性的值需要是一個編譯時常量,這意味着即使使用靜態類的靜態屬性也無濟於事。
正如dtb所建議的那樣,您可以停止使用DisplayName
-attribute來獲取顯示名稱,而是在要評估DisplayName
屬性的值處創建自己的機制。
在哪裏使用DisplayNameAttribute?你可以在那裏更改代碼嗎? – dtb
AFAIK DisplayName用於編譯,所以它必須是常數http://stackoverflow.com/a/9434934/1714342 – wudzik
可能重複[DisplayAttribute名稱與變量,動態顯示名稱](http://stackoverflow.com/questions/9434918/displayattribute-name-with-a-variable-dynamic-displayname) – wudzik