首页 > 解决方案 > 如何判断哪个 WPF 控件调用了命令?

问题描述

我有三个与同一命令关联的按钮:

<StackPanel>
    <Button Name="Btn1" Content="Test 1" Command="{Binding CmdDoSomething}" />
    <Button Name="Btn2" Content="Test 2" Command="{Binding CmdDoSomething}" />
    <Button Name="Btn3" Content="Test 3" Command="{Binding CmdDoSomething}" />
</StackPanel>

如何判断哪个 Button 调用了命令或将此信息传递给方法调用?

CmdDoSomething = new DelegateCommand(
    x => DvPat(),
    y => true
);

这是我的 DelegateCommand 类:

public class DelegateCommand : ICommand
{
    public event EventHandler CanExecuteChanged;
    public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);

    private readonly Predicate<object> _canExecute;
    public bool CanExecute(object parameter) => _canExecute == null ? true : _canExecute(parameter);

    private readonly Action<object> _execute;
    public void Execute(object parameter) => _execute(parameter);

    public DelegateCommand(Action<object> execute) : this(execute, null) { }
    public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

}

标签: c#wpf

解决方案


命令范例DelegateCommand包含参数,您可以将其传递给带有CommandParameter属性的处理程序并在处理程序中使用它:

<StackPanel>
    <Button Name="Btn1" Content="Test 1" Command="{Binding CmdDoSomething}" CommandParameter="Test 1" />
    <Button Name="Btn2" Content="Test 2" Command="{Binding CmdDoSomething}" CommandParameter="Test 2" />
    <Button Name="Btn3" Content="Test 3" Command="{Binding CmdDoSomething}" CommandParameter="Test 3" />
</StackPanel>

CmdDoSomething = new DelegateCommand(
    parameter => DvPat(parameter),
    y => true
);

此参数还可用于评估命令在CanExecute(object param)调用时的状态。


推荐阅读