UIHintAttribute 透過 ModelMetadata.TemplateHint 指定模板名稱,支援 PresentationLayer 區分呈現層(HTML、Silverlight、WPF 等)。本文詳細說明屬性定義、多重特性選擇邏輯與實測驗證。
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple=true)]
public class UIHintAttribute : Attribute
{
public string UIHint { get; } // 模板名稱
public string PresentationLayer { get; } // 呈現層類型
public UIHintAttribute(string uiHint);
public UIHintAttribute(string uiHint, string presentationLayer);
}
ModelMetadata.TemplateHint 對應 UIHint 屬性值,決定模板搜尋名稱。
PresentationLayer == "MVC"(不分大小寫)的特性PresentationLayer == null/Empty 的特性public static ModelMetadata GetModelMetadata<TModel>(string propertyName)
{
var provider = ModelMetadataProviders.Current;
var container = new ModelMetadata(provider, null, () => null, typeof(TModel), null);
return container.Properties.FirstOrDefault(m => m.PropertyName == propertyName);
}
public class Model
{
public string Foo { get; set; }
[UIHint("Template A")]
[UIHint("Template B", "Mvc")]
public string Bar { get; set; }
[UIHint("Template A")]
public string Baz { get; set; }
}
// 測試輸出
Console.WriteLine("Foo: " + (GetModelMetadata<Model>("Foo").TemplateHint ?? "N/A")); // N/A
Console.WriteLine("Bar: " + (GetModelMetadata<Model>("Bar").TemplateHint ?? "N/A")); // Template B
Console.WriteLine("Baz: " + (GetModelMetadata<Model>("Baz").TemplateHint ?? "N/A")); // Template A
結果完全符合選擇策略:Bar 選擇 PresentationLayer="Mvc" 的 Template B;Baz 單一特性直接使用 Template A。
PresentationLayer="MVC" 避免歧義