3

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

 public void SelectItem(object o, EventArgs e)

我怎样才能将额外的参数传递给执行?

我在 xaml 中完成了以下编码

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

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

会给 Command="SelectedItem" 工作吗?还是我应该在这里添加绑定条款?

提前致谢

4

3 回答 3

4

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

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;
     } 
   }
}
于 2012-02-29T10:17:32.313 回答
2

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

有关类似问题,请参见此处:

如果我们不能绑定 MouseBinding 的 Command,我们应该怎么做?

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

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

于 2012-02-29T11:31:30.110 回答
1

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

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

然后,您传递给 CommandParameter 的任何内容都将是传递给 Execute 的额外参数。

于 2012-02-29T10:12:00.133 回答