【问题标题】:Connecting mouse events with ViewModel via MouseBinding通过 MouseBinding 将鼠标事件与 ViewModel 连接起来
【发布时间】:2012-02-29 10:00:53
【问题描述】:

我有一个用户控件,其中包含一些 Telerik 控件。我编写了一个所有业务逻辑所在的视图模型。我需要拦截 Leftbuttondown 事件以了解用户何时单击 Telerik 控件。我尝试使用 MouseBinding 技术将 Leftbuttondown 绑定到视图模型中的事件处理程序。我不确定事件处理程序的签名是什么。我从某处读到,要绑定的命令应该是 ICommand 类型,而 Execute 方法只需要一个参数。 Leftbuttondown 事件的签名类似于

 public void SelectItem(object o, EventArgs e)

如何将额外的参数传递给 Execute?

我在 xaml 中完成了以下编码

    <telerik:RadTransitionControl.InputBindings>
        <MouseBinding Gesture="LeftClick" Command="SelectedItem" />
    </telerik:RadTransitionControl.InputBindings>

我应该如何在 ViewModel 中定义 SelectedItem?

给 Command="SelectedItem" 会起作用吗?还是我应该在这里添加 Binding 子句?

提前致谢

【问题讨论】:

标签: c# wpf xaml command icommand


【解决方案1】:

首先你需要某种RelayCommand 来实现System.Windows.Input.ICommand。这将帮助您进行绑定。

XAML

<MouseBinding Gesture="LeftClick" Command="{Binding SelectedItemCommand}" />

视图模型

class YourViewModel
{
   public void SelectItem(object o)
   {       }

   private ICommand selectedItemCommand
   public ICommand SelectedItemCommand 
   {
     get
     {
        if(selectedItemCommand == null)
        { 
          // RelayCommand will point to SelectItem() once mouse is clicked
          selectedItemCommand = new RelayCommand(SelectItem);
        }

        return selectedItemCommand;
     } 
   }
}

【讨论】:

    【解决方案2】:

    问题在于 MouseBinding 的 Command 属性不是 DependencyProperty,因此您无法将某些内容绑定到它。

    类似问题请看这里:

    If we can't bind a MouseBinding's Command, what are we supposed to do?

    基本上,根据对该问题的公认答案,您必须使用 AttachedCommandBehavior 而不是 MouseBinding 来实现您想要的。在我看来,如果这是你经常做的事情,那将是最好的方法。

    或者,如果这是您代码中唯一这样做的情况,我认为在后面的代码中处理事件并从那里调用视图模型的命令不会有什么坏处。 MVVM 纯粹主义者可能不同意,但有时最好以简单的方式做事,而不是让自己陷入困境,试图让你的代码完全空白!

    【讨论】:

    • 根据您链接到的问题的另一个答案,该命令现在是 .NET 4 中的 DependencyProperty。
    • 是的,它现在是一个 DependencyProperty。
    【解决方案3】:

    Command 值应该是一个绑定,而不仅仅是一个属性名:

    <MouseBinding Gesture="LeftClick" Command="{Binding SelectedItem}" CommandParameter="..." />
    

    那么你传递给 CommandParameter 的任何东西都将是传递给 Execute 的额外参数。

    【讨论】:

    • 我收到一个错误“无法在“MouseBinding”类型的“命令”属性上设置“绑定”。只能在 DependencyObject 的 DependencyProperty 上设置“绑定”。”
    • 啊,抱歉。我以为你已经在视图模型中设置了一个命令。您需要设置 DelegateCommand 类,如下所述:wpftutorial.net/DelegateCommand.html,然后绑定到名为 SelectedItemCommand 的命令,该命令的类型为 DelegateCommand。
    • 谢谢,但是我已经有了 ICommand 派生类,当我将该类的对象绑定到 MouseBinding 时会引发异常
    • 啊,好吧,我看错了你的错误信息。那么请参阅我对这个问题的替代答案。
    猜你喜欢
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 2021-09-14
    相关资源
    最近更新 更多