1.先新建一个ViewModelBase类,继承于INotifyPropertyChanged接口类:
namespace leason2
{
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
MainViewModel类继承于ViewModelBase类,定义两个属性,分别在set块中加入OnPropertyChanged():
namespace leason2
{
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
ShowCommand = new MyCommand(Show);
}
private string m_name;
public string Name
{
get { return m_name; }
set
{
m_name = value;
OnPropertyChanged();
}
}
private string m_title;
public string Title
{
get { return m_title; }
set
{
m_title = value;
OnPropertyChanged();
}
}
public MyCommand ShowCommand { get; set; }
public void Show()
{
Name = "点击了按钮";
Title = "我是标题";
}
}
}
Mainwindow.xaml中绑定上述两个属性:
<Grid>
<StackPanel>
<TextBox Text="{Binding Name}"/>
<TextBox Text="{Binding Title}"/>
<Button Command="{Binding ShowCommand}"/>
</StackPanel>
</Grid>
点击按钮,实现Show方法后,TextBox实现打印两个属性文字打印。