【问题标题】:Using a single generic Command for handling multiple Buttons使用单个通用命令来处理多个按钮
【发布时间】:2012-02-15 11:27:21
【问题描述】:

我正在构建一个简单的计算器应用程序。我还在学习如何在我的应用中应用 MVVM 模式。

我希望我的计算器的每个“数字”按钮都绑定到同一个命令,它们只会在发出命令的按钮的数字(文本)上有所不同。

例如,当按钮“1”被点击时,我想收到有关它的通知,从 Sender 的属性中提取“1”,然后继续所需的其余工作。

这允许我定义一个方法而不是 10 个不同的处理程序。

就目前为止我在所有 MVVM 教程中看到的而言,这是不可能的,因为当绑定到将处理点击的实际方法时,Command 绑定不会向我提供所有这些信息。

有什么方法可以轻松满足我的要求吗?

【问题讨论】:

    标签: c# .net wpf binding mvvm


    【解决方案1】:

    假设我了解您要执行的操作,您可以使用 CommandParameter 属性让不同的按钮为同一命令提供值。例如:

    ...
        <Button Content="1" Command="{Binding ButtonClickCommand}" CommandParameter="1"/>
    
        <!-- Or, bind directly to the button's content using RelativeSource, like so: -->
        <Button Content="2" Command="{Binding ButtonClickCommand}"                    
                            CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}"/>
    ...
    

    在你的命令的委托方法中:

    private void ButtonClickCommandHandler(object parameter)
    {
        switch(int.Parse(parameter.ToString()))
        {
            case 1:
            ...
            case 2:
            ...
        }
    }
    

    【讨论】:

    • 谢谢,这就是我所做的。两个小问题——我可以只引用一次按钮的内容吗?意思是,在 CommandParameter 中“引用”内容而不是再次编写它?第二个问题 - 作为 CommandParameter 传递的参数的运行时类型是什么?是怎么确定的?
    • @liortal: CommandParameter="{Binding Content, RelativeSource={RelativeSource Self}}"
    • CommandParameter 似乎作为string 传递,因此处理程序应该使用int.Parse 来检索整数。我已更新我的答案以解决您的问题。
    【解决方案2】:

    只需将数字提供为Button.CommandParameter。 (作为ICommand.Execute(和CanExecute)的方法参数传递)

    【讨论】:

      猜你喜欢
      • 2023-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多