如何识别点击了哪个按钮?(MVVM)

Kyl*_*Ren 5 c# wpf button mvvm

继续沿着MVVM的路径前进,我来到了按钮命令.经过相当多的反复试验后,我终于得到了一个Button_Click使用命令的工作示例ICommand.

我的问题是,现在我有一个通用事件,我无法获得点击哪个按钮来应用一些逻辑.在我的例子中,我没有使用任何可以获取Sender信息的地方.通常如下所示RoutedEventArgs:

Button button = (Button)sender;
Run Code Online (Sandbox Code Playgroud)

所以这就是我到目前为止所拥有的.

ICommand类:

public class CommandHandler : ICommand
{
    private Action _action;
    private bool _canExecute;
    public CommandHandler(Action action, bool canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        _action();
    }
}
Run Code Online (Sandbox Code Playgroud)

以及执行操作的代码:

private ICommand _clickCommand;
public ICommand ClickCommand => _clickCommand ?? (_clickCommand = new CommandHandler(MyAction, _canExecute));

public ViewModelBase()
{
    _canExecute = true;            
}

public void MyAction()
{
    //Apply logic here to differentiate each button
}
Run Code Online (Sandbox Code Playgroud)

和XAML,

<Button Command="{Binding ClickCommand}" Style="{StaticResource RedButtonStyle}">MyButton</Button>
Run Code Online (Sandbox Code Playgroud)

在将相同命令绑定到其他按钮时,如何识别单击哪个按钮?

Xan*_*ano 5

可能不应该,但如果你,你可以使用CommandParameter=""

不过,您应该只使用 2 个 ICommand。

XAML:

<Button Command="{Binding ClickCommandEvent}" CommandParameter="Jack"/>

视图模型:

public RelayCommand ClickCommandEvent { get; set; }

public SomeClass()
{
    ClickCommandEvent = new RelayCommand(ClickExecute);
}

public void ClickExecute(object param)
{
    System.Diagnostics.Debug.WriteLine($"Clicked: {param as string}");

    string name = param as string;
    if (name == "Jack")
        HighFive();
}
Run Code Online (Sandbox Code Playgroud)

你的 RelayCommand 类就是这个样板

public class RelayCommand : ICommand
{
    #region Fields
    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;

    #endregion

    #region Constructors
    public RelayCommand(Action<object> execute) : this(execute, null) { }

    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }
    #endregion

    #region ICommand Members
    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }
    #endregion
}
Run Code Online (Sandbox Code Playgroud)