赞
踩
定义一个类,例如Student 需要继承INotifyPropertyChanged,
详细的说明如代码中的说明
- public class Student:INotifyPropertyChanged
- {
- string _name="";
- public string Name
- {
- get
- {
- return _name;
- }
- set
- {
- _name=value;
- //需要通知UI改变的变量,在这里调用你定义的函数
- OnPropertyChanged("Name");
- }
- }
-
- //这个是INotifyPropertyChanged接口中的变量
- public event PropertyChangedEventHandler PropertyChanged;
-
- //自定义一个函数OnPropertyChanged(函数名字任意)
- protected void OnPropertyChanged(string propertyName = null)
- {
- //发出事件通知UI
- PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
界面绑定
- <Grid>
- <TextBlock x:Name="textBlock1" Text="{Binding Name}" />
- </Grid>
- class MainWindow : Window
- {
-
- public Student student;
- public MainWindow()
- {
- InitializeComponent();
-
- student = new Student();
- this.DataContext = student; //设置上下文为student 这样textbox能找到Name的属性
-
-
- student.PropertyChanged += Student_PropertyChanged;//代码中也可以订阅一下属性改变
- 做替他的操作 这个和UI更新无关
-
- }
-
- private void Student_PropertyChanged(object sender,
- System.ComponentModel.PropertyChangedEventArgs e)
- {
- //"属性值改变了";
- }
-
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。