在这里将演示一个最基础的WPF的Binding示例:将一个类和一个控件进行绑定。this
首先建立一个名为Student的类,这个类的实例将做为数据源。code
class Student { private string name; public string Name { get { return name;} set { name = value;} } }
为了让Student的实例的值,在发生变化后能通知Binding,因此在属性的 set语句中激发一个PropertyChanged事件,所以要实现INotifyPropertyChanged接口。xml
class Student : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string name; public string Name { get { return name; } set { name = value; //激发事件 if(null != PropertyChanged) { this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name")); } } } }
而后咱们咱们在窗体上准备一个TextBox和一个Button。TextBox将做为Binding的目标,咱们会在Button的Click事件发生时改变Student对象的Name属性值。对象
<Window x:Class="Test01.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Binding" Height="110" Width="300"> <StackPanel Background="Gray" Height="Auto"> <TextBox x:Name="textBoxName" BorderBrush="Black" Margin="5" Height="25" FontSize="15"/> <Button Content="点击" Click="Button_Click" Margin="5" Height="25" /> </StackPanel> </Window>
public partial class MainWindow : Window { Student stu; public MainWindow() { InitializeComponent(); //准备数据源 stu = new Student(); //准备Binding Binding binding = new Binding(); binding.Source = stu; binding.Path = new PropertyPath("Name"); //使用Binding链接数据源与Bindin目标 BindingOperations.SetBinding(this.textBoxName, TextBox.TextProperty, binding); } private void Button_Click(object sender, RoutedEventArgs e) { stu.Name += "Name__"; } }