屬性亦是WPF數據驅動UI理念的核心之一
自定義依賴屬性
實現兩個控件之間通過依賴對象中的依賴屬性關聯
- XAML:
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox x:Name="tb1" Width="200" Height="30"
Grid.Row="0"/>
<TextBox x:Name="tb2" Width="200" Height="30"
Grid.Row="1"/>
-
效果圖:
-
派生自依賴對象的自定義類:
快捷鍵 propdp
class Student : DependencyObject
{
public string Name
{
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
public static readonly DependencyProperty NameProperty =
DependencyProperty.Register("Name", typeof(string), typeof(Student));
public BindingExpressionBase SetBinding(DependencyProperty dp,
BindingBase binding)
{
return BindingOperations.SetBinding(this, dp, binding);
}
}
- 核心部分關聯控件:
Student student = new Student();
student.SetBinding(Student.NameProperty, new Binding("Text") { Source = tb1 });
tb2.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = student });
- 動圖效果演示:
- 核心概念:
DependencyProperty 對象的創建與清冊:
創建一個DependencyProperty
實例並用它的 CLR 屬性和宿主類型名生成hash code
,最後把 hash code 和 DependencyProperty 實例作爲Key - Value
對存入全局的、名爲PropertyFromName
的 **Hashtable
**中;
這樣, WPF屬性系統通過 **
屬性名和宿主類型名
**就可以從這個全局的 Hashtable 中檢索
出對應的 DependencyProperty 實例。
最後,生成的 DependencyProperty 實例被當作返回值交還:
return dp;
自定義附加屬性
附加屬性的本質亦是依賴屬性,在特定的場合是個屬性可起作用
創建兩個依賴對象,將一個附加屬性附加到另一個依賴對象上
- 被附加的對象:
class Huameng : DependencyObject
{
...
}
- 擁有附加屬性的依賴對象:
快捷鍵 propa
class Student : DependencyObject
{
public static int GetGrade(DependencyObject obj)
{
return (int)obj.GetValue(GradeProperty);
}
public static void SetGrade(DependencyObject obj, int value)
{
obj.SetValue(GradeProperty, value);
}
public static readonly DependencyProperty GradeProperty =
DependencyProperty.RegisterAttached(
"Grade",
typeof(int),
typeof(Student),
new PropertyMetadata(0)
);
}
- 測試代碼:
Huameng huameng = new Huameng();
Student.SetGrade(huameng, 20);
int num = Student.GetGrade(huameng);
MessageBox.Show(num.ToString());
- 效果圖:
看到這些代碼我們發現和依賴屬性保存值的過程別無二致 ——
值被保存在 Huameng實例的 EffectiveValueEntry 數組裏;
用於在數組檢索值的依賴屬性(附加屬性)並不以 Huameng類爲宿主而是寄宿在 Student類裏。