如何在视图模型中为2个不同的按钮使用2个不同的命令。
我的要求是在我的页面中使用2个按钮。
我已实现1个按钮,但无法实现多个按钮。
任何人都可以提供一个使用MVVM在viewmodel中使用多个命令的示例。
我是MVVM的新手,所以请帮帮我。
答案 0 :(得分:1)
1)创建RelayCommand类:
public class RelayCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public RelayCommand(Predicate<object> canExecute, Action<object> execute)
{
this._canExecute = canExecute;
this._execute = execute;
}
public event EventHandler CanExecuteChanged
{
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
public bool CanExecute(object parameter)
{
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
}
2)在VM中创建ICommand属性:
public ICommand Command1 { get { return new RelayCommand(e => true, this.MethodForCommand1); } }
public ICommand Command2{ get { return new RelayCommand(e => true, this.MethodForCommand2); } }
private void MethodForCommand1(object obj){ //Type your code for Command1 }
private void MethodForCommand2(object obj){ //Type your code for Command2 }
3)视图中的绑定命令:
<Button Content="Button 1" Command="{Binding Command1}"/>
<Button Content="Button 2" Command="{Binding Command2}"/>
希望它有所帮助;)