依賴屬性是WPF(Windows Presentation Foundation)中的一種特殊類型的屬性,特別適用于內存使用優化和屬性值繼承。依賴屬性的定義包括以下幾個步驟:
使用 DependencyProperty.Register 方法注冊依賴屬性。
該方法需要四個參數:
第一個參數是依賴屬性的名稱,這里為 “Age”。
第二個參數是依賴屬性的數據類型,這里為 typeof(int)。
第三個參數是擁有該依賴屬性的類的類型,這里為 typeof(DataModel)。
第四個參數是屬性的元數據,通過 PropertyMetadata 類傳遞,這里設置了默認值 18。
依賴屬性通過 GetValue 和 SetValue 方法進行訪問和修改,而不是通過簡單的getter和setter,這使得它們可以參與WPF的數據綁定、樣式繼承等高級功能
public static readonly DependencyProperty AgeProperty =
DependencyProperty.Register("Age", typeof(int), typeof(MainWindow), new PropertyMetadata(18));
// 包裝器:把依賴屬性AgeProperty包裝一下,可以理解成給依賴屬性AgeProperty添加一個“外殼”。
// 添加“外殼”后讓依賴屬性用起來和普通屬性一個用法。
// B。依賴屬性的包裝器:
public int Age{get { return (int)GetValue(AgeProperty); }set { SetValue(AgeProperty, value); }}
C. 屬性的使用
給當前的XAML文檔綁定上下文寫法1:默認支持智能感知
只有給XAML文檔綁定了上下文后,XAML文檔中才能使用上下文對象中提供的數據(屬性等)
<Window.DataContext><local:DataModel />
</Window.DataContext><StackPanel><ButtonWidth="100"Height="30"Content="{Binding Path=Age}" /><ButtonWidth="100"Height="30"Content="{Binding MyProperty}" /></StackPanel>
DataModel
public class DataModel : Window{public int MyProperty { get; set; } = 100;// A。依賴屬性的定義又叫依賴屬性注冊。通過DependencyProperty.Register()方法。// 方法參數:// 1.屬性名// 2.屬性類型// 3.依賴屬性所屬的類// 4.屬性元數據,依賴屬性的默認值public static readonly DependencyProperty AgeProperty =DependencyProperty.Register("Age", typeof(int), typeof(MainWindow), new PropertyMetadata(18));// 包裝器:把依賴屬性AgeProperty包裝一下,可以理解成給依賴屬性AgeProperty添加一個“外殼”。// 添加“外殼”后讓依賴屬性用起來和普通屬性一個用法。// B。依賴屬性的包裝器:public int Age{get { return (int)GetValue(AgeProperty); }set { SetValue(AgeProperty, value); }}}