在您的 XAML 中:
<Button Content="My Button" Command="{Binding MyViewModelCommand}" />
在您的视图模型中:
public class MyViewModel
{
public MyViewModel()
{
MyViewModelCommand = new ActionCommand(DoSomething);
}
public ICommand MyViewModelCommand { get; private set; }
private void DoSomething()
{
// no, seriously, do something here
}
}
INotifyPropertyChanged
并且省略了其他视图模型的寒暄。
在视图模型中构造命令的另一种方法显示在此答案的底部。
现在,您需要一个ICommand
. 我建议从像这样简单的东西开始,并根据需要扩展或实现其他功能/命令:
public class ActionCommand : ICommand
{
private readonly Action _action;
public ActionCommand(Action action)
{
_action = action;
}
public void Execute(object parameter)
{
_action();
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
}
这是布局视图模型的另一种方法:
public class MyViewModel
{
private ICommand _myViewModelCommand;
public ICommand MyViewModelCommand
{
get
{
return _myViewModelCommand
?? (_myViewModelCommand = new ActionCommand(() =>
{
// your code here
}));
}
}
}