1. 程式人生 > 其它 >WPF中關於依賴屬性的使用

WPF中關於依賴屬性的使用

關於依賴屬性的使用大體分為兩個步驟:

1、在類中用 public 宣告要依賴的屬性,並使用 DependencyProperty.Register方法獲取DependencyProperty的例項;

2、使用DependencyObject的setValue和GetValue方法,藉助DependencyProperty例項來存取值。

通過程式碼示例:

後臺程式碼中, 建立一個Student類,其繼承DependencyObject

public 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)); //SetBinding包裝 public BindingExpressionBase SetBinding(DependencyProperty dp,BindingBase binding) {
return BindingOperations.SetBinding(this, dp, binding); } }
View Code

xaml介面程式碼為:

<Window x:Class="Wpf_Property.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:Wpf_Property" mc:Ignorable="d" Title="MainWindow" Height="135" Width="260"> <StackPanel> <TextBox x:Name="textBox1" BorderBrush="Black" Margin="5"/> <TextBox x:Name="textBox2" BorderBrush="Black" Margin="5"/> <Button Content="Ok" Margin="5" Click="Button_Click"/> </StackPanel> </Window>
View Code

其button_click事件程式碼:

private void Button_Click(object sender, RoutedEventArgs e)
        {
            Student student = new Student();
            student.SetValue(Student.NameProperty, this.textBox1.Text);
            textBox2.Text = (string)student.GetValue(Student.NameProperty);
        }
View Code

程式完成,在TextBox1中輸入內容,點選Button按鈕,在TextBox2中同步顯示。