【问题标题】:How to tell which WPF Control invoked a command? [duplicate]如何判断哪个 WPF 控件调用了命令? [复制]
【发布时间】:2019-01-22 15:36:08
【问题描述】:

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

<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;
    }

}

【问题讨论】:

  • 最简单的方法是将命令参数传递给命令。看看这个线程是如何完成的。 stackoverflow.com/questions/32064308/…
  • 另外,就其价值而言,您的 Command 对象不应该知道有关哪个控件调用该命令的任何信息。这就是首先拥有一个 Command 对象的全部意义所在。

标签: c# wpf


【解决方案1】:

Commands paradigmDelegateCommand 包含参数,您可以将其传递给具有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)时命令的状态。

【讨论】:

  • 完美,谢谢。我不知道CommandParameter
猜你喜欢
  • 1970-01-01
  • 2013-10-09
  • 2013-03-23
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 2016-11-14
  • 2013-09-23
  • 1970-01-01
相关资源
最近更新 更多