WPF附加屬性相關用途介紹
我們通過對WPF的深入學習,可以知道,WPF中的屬性可以分為兩種,一種是依賴屬性而另外一種則是附加屬性。我們在這里將會重點介紹WPF附加屬性。#t#
WPF附加屬性是允許不同的子元素為 實際在父元素中定義的屬性指定***值。例如:
- < 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);
如何創建WPF附加屬性
1. 聲明一個 DependencyProperty 類型的 public static readonly 字段,將附加屬性定義為一個依賴項屬性。
2. 使用 RegisterAttached 方法的返回值來定義此字段。例如:
- 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 自動生成基本內容:)