ICommand命令
MyCommand类
public class MyCommand : ICommand
{
private Action showAction;//声明一个事件,用于接收一个事件处理的方法
public MyCommand(Action action)
{
showAction = action;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
//这个方法在事件触发时调用
public void Execute(object parameter)
{
showAction();//调用自定义的事件
}
}
INotifyPropertyChanged通知
MainViewModelBase类
public class MainViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
//CallerMemberName:自动推导名称
public void OnPropertyChanged([CallerMemberName]string name="")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));//属性值改变的通知调用
}
}
应用
MainViewModel类
public class MainViewModel:MainViewModelBase
{
private string nameA;
public string NameA
{
get { return nameA; }
set
{
nameA = value;
OnPropertyChanged();//通知属性值已经改变,对应的Xaml标签值内容改变
}
}
//声明一个事件命令,需要添加get方法,Xaml才可以访问到,类型要public
public MyCommand ShowCommand { get; }
//
public MainViewModel()
{
ShowCommand = new MyCommand(show);//创建一个命令对象
}
//具体的事件处理方法
public void show()
{
NameA = "点击了按钮";
MessageBox.Show("点击了按钮");
}
}
MainWindow类构造方法
public MainWindow()
{
InitializeComponent();
//数据上下文赋值
this.DataContext = new MainViewModel();
}
MainWindow.xaml文件
<DockPanel>
<!-- 绑定MainViewModel的NameA属性,当NameA属性值发生变化时,标签内容改变 -->
<TextBox Text="{Binding NameA}" DockPanel.Dock="Top"></TextBox>
<!-- 绑定ShowCommand命令,当Button被点击时,调用show方法 -->
<Button Command="{Binding ShowCommand}"></Button>
</DockPanel>