wpf 自定义依赖性属性 作用之一 对数据绑定的支持

依赖属性:定义,声明,注册 

依赖属性,在数据绑定中,数据绑定,分为源对象(数据源)和目标对象(显示数据)。

只有源对象为依赖对象,属性为依赖属性时,该属性才会在属性发生变化时,通知目标对象进行数据更改。

依赖属性,具有对目标对象更改通知的功能。

XAML

<StackPanel>
<TextBox Style="{StaticResource textStyle}" Height="37" Name="textBox1" FontSize="26" Margin="5" Width="439" />
<TextBox Style="{StaticResource textStyle}" Height="37" Name="textBox2" FontSize="26" Margin="5" Width="439" />
<Button Content="Button" Height="39" Name="button1" Width="131" Click="button1_Click" />
</StackPanel>

.CS

namespace WPF_VIP_Characters
{
/// <summary>
/// Interaction logic for DependProperty.xaml
/// </summary>
public partial class DependProperty : Window
{
public DependProperty()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
//Student stu = new Student();
//stu.SetValue(Student.NameProperty, textBox1.Text);
//textBox2.Text = (string)stu.GetValue(Student.NameProperty);

Student stu = new Student();

Binding binding = new Binding("Text") { Source = textBox1 };
BindingOperations.SetBinding(stu, Student.NameProperty, binding);

Binding binding2 = new Binding("Name") { Source = stu };
BindingOperations.SetBinding(textBox2, TextBox.TextProperty, binding2);

}
}

class Student:DependencyObject
{
//CLR属性进行封装
public string Name
{
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
//定义依赖属性/注册
public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Student));
}

}

原文地址:https://www.cnblogs.com/wwwfj/p/3645319.html