wpf控制元件設計時支援(1)
這部分內容幾乎是大家忽略的內容,我想還是來介紹一下.
本篇原始碼下載
1.屬性元資料
在vs IDE中,在asp.net,winfrom等開發環境下,右側的PropertyGrid屬性面板,會對屬性進行分類,這有利於瞭解控制元件屬性的用途.
若你之前在.net平臺下做過控制元件開發,你應該知道這些功能是通過屬性元資料實現的,比如使用Category元資料,把Content屬性分到Content類別下.
[Category("Content")] public object Content { get; set; }
這種方法在開發wpf自定義控制元件依然可用.我們以名為DesginCustomControl的自定義控制元件為例子.因為是wpf控制元件,所以屬性變更為依賴項屬性.
public class DesginCustomControl : ContentControl { [Category("Content")] public string Content { get { return (string)GetValue(ContentProperty); } set { SetValue(ContentProperty, value); } } public static readonly DependencyProperty ContentProperty = DependencyProperty.Register("Content", typeof(string), typeof(DesginCustomControl), new UIPropertyMetadata(String.Empty)); }
效果如下:
2.屬性元資料集合
wpf的設計時允許我們將這些元資料與控制元件屬性分離出來.下面我們來實現一個簡單的功能
2.1新建一個設計時支援的單獨專案
WPF.Controls是控制元件專案,WPF.Controls.VisualStudio.Design是控制元件設計時專案
注意:
(1)程式集命名約定
設計時的程式集是有命名約定的,這樣才可以受到VisualStudio的支援.如控制元件程式集是WPF.Controls,那麼設計時程式集則是
控制元件程式集的名字+VisualStudio.Design
(2)設計時程式集編譯位置
設計時程式集必須與控制元件存放在同個目錄下才能工作,引用控制元件的專案無需引用設計時程式集
假設WPF.Controls的編譯目錄沒有做變更的話,那麼WPF.Controls.VisualStudio.Design這個專案編譯好後是存在在WPF.Controls的bin目錄下面的.
(3)引用Microsoft.Windows.Design程式集
Microsoft.Windows.Design是wpf設計時支援的基礎,所以要引用這個程式集
2.2註冊屬性的元資料集合
實現一個名為IRegisterMetadata的介面。來看一下程式碼
public class WPFControlsCommonMetadata : IRegisterMetadata { public void Register() { AttributeTableBuilder MainBuilder = new AttributeTableBuilder(); MainBuilder.AddCustomAttributes(typeof(DesginCustomControl),DesginCustomControl.ContentProperty,new Attribute[]{ new CategoryAttribute("Content")}); MetadataStore.AddAttributeTable(MainBuilder.CreateTable()); } }
AttributeTableBuilder是屬性元資料表,msdn是解釋屬性表.AttributeTableBuilder有多個AddCustomAttributes過載方法.可以將元資料附加到屬性上.比如上面程式碼給DesginCustomControl的Content屬性添加了一個CategoryAttribute元資料.新增完畢以後再通過
MetadataStore的AddAttributeTable方法新增屬性元資料表.MetadataStore稱之為元資料儲存區.
以上程式碼的實現與在控制元件上直接掛元資料標籤效果是一樣.有什麼不同點呢?
若我們為asp.net的內建控制元件擴充套件設計時的話,則必須繼承該控制元件.這裡便不會有這個問題,兩者是完全分離的.
2.3延遲新增屬性元資料
上面的示例,直接在MainBuilder類中為控制元件新增元資料,當為比較多的控制元件新增元資料時,同時載入會出現效能問題,所以MainBuilder還提供了AddCallback方法,當需要時,才會為控制元件新增元資料.現以上示例程式碼變更如下
public class WPFControlsCommonMetadata : IRegisterMetadata { public void Register() { AttributeTableBuilder MainBuilder = new AttributeTableBuilder(); MainBuilder.AddCallback( typeof(DesginCustomControl), delegate(AttributeCallbackBuilder builder) { builder.AddCustomAttributes(DesginCustomControl.ContentProperty, new Attribute[]{ new CategoryAttribute("Content")}); }); MetadataStore.AddAttributeTable(MainBuilder.CreateTable()); } }
是不是感覺很無聊,為了這麼個東西還要去研究:),覺得的有用的就看一下吧,這篇就寫這麼多,寫完就差不多可以放假回家了.