Binding 作为数据的桥梁,分为Binding的源(source)和目标(target)
Binding是一种自动机制,当值变化后能通知,要实现需要在数据源的对象实现INotifyPropertyChanged接口
public class Student : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string name; public string Name { get { return name; } set { name = value; //激发事件 if (this.PropertyChanged != null) { this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name")); } } } }
表示层 xaml
<TextBox x:Name="text" Grid.ColumnSpan="3" BorderBrush="Black" />
后置cs
private Student s; public MainWindow() { s = new Student(); InitializeComponent(); Binding binding = new Binding(); binding.Source = s; binding.Path = new PropertyPath("Name"); BindingOperations.SetBinding(this.text, TextBox.TextProperty, binding); // this.text.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = s }); //等同上面绑定 }
这样就实现数据绑定
以控件作为数据源绑定
Path 路径 ElementName源 Mode 数据更新方向 (TwoWay、OneWay、OneWayToSource、Default)默认双向,UpdateSourceTrigger 触发更新(LostFoucs、Explicit、Default,PropertyChanged)