《15天玩轉WPF》—— 自定義( 依賴 / 附加 ) 屬性示例

屬性亦是WPF數據驅動UI理念的核心之一


自定義依賴屬性

實現兩個控件之間通過依賴對象中的依賴屬性關聯

  1. 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"/>
  1. 效果圖:
    在這裏插入圖片描述

  2. 派生自依賴對象的自定義類:

快捷鍵 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);
	}
}
  1. 核心部分關聯控件:
Student student = new Student();
student.SetBinding(Student.NameProperty, new Binding("Text") { Source = tb1 });
tb2.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = student });
  1. 動圖效果演示:

在這裏插入圖片描述

  1. 核心概念:

DependencyProperty 對象的創建與清冊:
創建一個 DependencyProperty 實例並用它的 CLR 屬性和宿主類型名生成 hash code,最後把 hash code 和 DependencyProperty 實例作爲 Key - Value 對存入全局的、名爲 PropertyFromName 的 **Hashtable**中;

這樣, WPF屬性系統通過 **屬性名和宿主類型名**就可以從這個全局的 Hashtable 中 檢索 出對應的 DependencyProperty 實例。
最後,生成的 DependencyProperty 實例被當作返回值交還:
return dp;


自定義附加屬性

附加屬性的本質亦是依賴屬性,在特定的場合是個屬性可起作用

創建兩個依賴對象,將一個附加屬性附加到另一個依賴對象上

  1. 被附加的對象:
class Huameng : DependencyObject
{
	...
}
  1. 擁有附加屬性的依賴對象:

快捷鍵 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)
                );
}
  1. 測試代碼:
Huameng huameng = new Huameng();
Student.SetGrade(huameng, 20);
int num = Student.GetGrade(huameng);
MessageBox.Show(num.ToString());
  1. 效果圖:

在這裏插入圖片描述

看到這些代碼我們發現和依賴屬性保存值的過程別無二致 ——
值被保存在 Huameng實例的 EffectiveValueEntry 數組裏;
用於在數組檢索值的依賴屬性(附加屬性)並不以 Huameng類爲宿主而是寄宿在 Student類裏。


作者:浪子花夢

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章