【WPF】七、通知更改INotifyPropertyChanged
首先要继承INotifyPropertyChanged
简单方式在赋值的时候调用PropertyChanged
namespace WpfApp1
{
public class MainViewModel:INotifyPropertyChanged
{
public MyCommand ShowCommand { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public string Name
{
get { return name; }
set { name = value;
//通知客户端内容更改的方式一种
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Name"));
}
}
public string name;
public MainViewModel()
{
Name = "Hello World";
ShowCommand = new MyCommand(Show);
}
public void Show()
{
Name = "点击了Button";
MessageBox.Show(Name);
}
}
}
方式二:自动绑定
封装一个事件调用OnPropertyChanged
namespace WpfApp1
{
public class MainViewModel:INotifyPropertyChanged
{
public MyCommand ShowCommand { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string propertyName="")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string Name
{
get { return name; }
set { name = value;
//通知客户端内容更改的方式一种
OnPropertyChanged();
}
}
public string name;
public MainViewModel()
{
Name = "Hello World";
ShowCommand = new MyCommand(Show);
}
public void Show()
{
Name = "点击了Button";
MessageBox.Show(Name);
}
}
}