在这里将演示一个最基础的WPF的Binding示例:将一个类和一个控件进行绑定。
效果预览
类的准备
首先创建一个名为Student的类,这个类的实例将作为数据源。
class Student
{
private string name;
public string Name
{
get { return name;}
set { name = value;}
}
}
为了让Student的实例的值,在发生变化后能通知Binding,所以在属性的 set语句中激发一个PropertyChanged事件,因此要实现INotifyPropertyChanged接口。
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"));
}
}
}
}
UI元素的准备
然后我们我们在窗体上准备一个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>
数据源与UI元素的连接
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__";
}
}