Binding可以让前台和后台的属性绑定在一起。实现实时更新。
比如
前台xaml
<StackPanel> <TextBox x:Name="txtBox" BorderBrush="Black" Margin="5"/> <Button Margin="5" Content="点击" Click="Button_Click"/> </StackPanel>
后台
先声明一个用于绑定数据的类,需要继承自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")); } } } }
然后声明
//全局变量,监控值变化 Student stu; public FirstWindow() { InitializeComponent(); //数据源 stu = new Student(); //声明绑定属性 Binding binding = new Binding(); binding.Source = stu; binding.Path = new PropertyPath("Name"); //这里指明 绑定的是Student的Name属性 //将数据源和binding绑在一起 //这条语句将txtBox对象的Text属性和 Student的Name属性绑在一起 BindingOperations.SetBinding(txtBox,TextBox.TextProperty, binding); } private void Button_Click(object sender, RoutedEventArgs e) { //这里全局的Student属性才能变化 stu.Name += "Hello "; }
标签:Name,Binding,binding,Student,new,WPF,属性 From: https://www.cnblogs.com/AduBlog/p/17216796.html