在您的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
}));
}
}
}
来源
2012-08-30 19:54:02
Jay
谢谢周杰伦这是正是我正在寻找:)飞机和简单:) –