WPF附加屬性相關(guān)用途介紹
我們通過(guò)對(duì)WPF的深入學(xué)習(xí),可以知道,WPF中的屬性可以分為兩種,一種是依賴屬性而另外一種則是附加屬性。我們?cè)谶@里將會(huì)重點(diǎn)介紹WPF附加屬性。#t#
WPF附加屬性是允許不同的子元素為 實(shí)際在父元素中定義的屬性指定***值。例如:
- < DockPanel>
- < CheckBox DockPanel.
Dock="Top">Hello
< /CheckBox> - < /DockPanel>
Dock不是CheckBox的屬性,而是定義在DockPanel中的。
用代碼使用:
- DockPanel myDockPanel =
new DockPanel();- CheckBox myCheckBox =
new CheckBox();- myCheckBox.Content =
"Hello";- myDockPanel.Children.
Add(myCheckBox);- DockPanel.SetDock
(myCheckBox, Dock.Top);
如何創(chuàng)建WPF附加屬性
1. 聲明一個(gè) DependencyProperty 類型的 public static readonly 字段,將附加屬性定義為一個(gè)依賴項(xiàng)屬性。
2. 使用 RegisterAttached 方法的返回值來(lái)定義此字段。例如:
- public class OwerClass :
DependencyObject- {
- public static string
GetAttachedPropertyName
(DependencyObject obj)- {
- return (string)obj.GetValue
(AttachedPropertyNameProperty);- }
- public static void SetAttached
PropertyName(DependencyObject
obj, string value)- {
- obj.SetValue(AttachedProperty
NameProperty, value);- }
- public static readonly
DependencyProperty Attached
PropertyNameProperty =- DependencyProperty.RegisterAttached
("AttachedPropertyName",
typeof(string), typeof(OwerClass),
new UIPropertyMetadata(0));- }
WPF附加屬性小提示:
可以利用VS2008智能提示:在class里面輸入propa,然后按Tab 自動(dòng)生成基本內(nèi)容:)