標籤:
1、什麼是相依性屬性
相依性屬性是一種可以自己沒有值,並且通過Binding從資料來源獲得值(依賴在別人身上)的屬性,擁有相依性屬性的對象被稱為“依賴對象”。
依賴項屬性通過調用 Register 方法(或 RegisterReadOnly)在 WPF 屬性系統中註冊,並通過 DependencyProperty 標識符標示屬性。 依賴項屬性只能由繼承自 DependencyObject 類的類型使用,在WPF中大部分的類都可以支援相依性屬性。
2、DependencyObject和DependencyPorperty
DependencyObject和DependencyPorperty兩個類是WPF屬性系統的核心
在WPF中,依賴對象的概念被DependencyObject類實現;相依性屬性的概念則由DependencyProperty類實現
必須使用依賴對象作為相依性屬性的宿主,二者結合起來,才能實現完整的Binding目標被資料所驅動。DependencyObject具有GetValue和SetValue兩個方法,用來擷取/設定相依性屬性的值。
DependencyProperty執行個體的聲明特點——引用變數由public static readonly三個修飾符修飾,執行個體不是new 操作符得到,而是調用DependencyProperty.Register方法產生。(見執行個體代碼)
3、範例程式碼
<Window x:Class="DependencyPropertyDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:DependencyPropertyDemo" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <StackPanel> <TextBox x:Name="textBox1" BorderBrush="Black" Margin="5"/> <TextBox x:Name="textBox2" BorderBrush="Black" Margin="5" Text="{Binding Path=Text, ElementName=textBox1,Mode=OneWay}"/> <Button Margin="5" Content="OK" Click="Button_Click"/> </StackPanel></Window>
聲明一個Student類,繼承DependencyObject,在裡面聲明一個屬性,即相依性屬性,命名規則是要以Property結尾。
為了方便使用,給他聲明了一個Name屬性,set中調用SetValue()方法設定Name,get中調用GetValue()方法擷取Name。
public class Student:DependencyObject {
/// <summary>
/// Register方法中各參數說明
/// 第一個參數為string類型,指明以那個CLR屬性作為相依性屬性的封裝器,這裡是Name,已經實現CLR屬性的封裝
/// 第二各參數為Type類型,用來指明次相依性屬性用來儲存什麼類型的值
/// 第三個參數為Type類型,指明相依性屬性宿主類型,或者說DependencyProperty.Register放啊分將把這個相依性屬性關聯到哪個類型上。
/// </summary>
public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Student)); public string Name { get { return (string)this.GetValue(Student.NameProperty); } set { this.SetValue(Student.NameProperty, value); } } }
Student stu; public MainWindow() { InitializeComponent(); stu = new Student(); Binding binding = new Binding("Text") { Source = textBox1 }; BindingOperations.SetBinding(stu, Student.NameProperty, binding); // textBox2.SetBinding(TextBox.TextProperty, binding); } private void Button_Click(object sender, RoutedEventArgs e) { MessageBox.Show(stu.Name); }
在MainWindow()中的最後兩行代碼,綁定Student執行個體和textbox,textbox作為資料來源,而Student執行個體作為目標,目標的屬性為NameProperty。
如此便實現了前台TextBox輸入字串和背景Student執行個體的資料繫結。
WPF——相依性屬性(Dependency Property)