Search code examples
c#wpfxamlcommandicommand

Connecting mouse events with ViewModel via MouseBinding


I have a user control having some telerik controls in it. I have a coded a ViewModel where all the business logic resides.

I need to intercept the LeftClick event to know when a user clicks on the telerik control. I tried using the MouseBinding technique to bind the LeftClick to the event handler in the ViewModel.

I am not sure about what the signature is for the event handler. I read somewhere that the command to bind should be of type ICommand and the execute method takes only one parameter.

The signature for the LeftClick event is:

public void SelectItem(object o, EventArgs e)

How can I pass the extra argument to the execute method?

I have written the following XAML:

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

How should I define SelectedItem in the ViewModel?

Will Command="SelectedItem" work? Or should I add a binding clause here?


Solution

  • The problem is that the MouseBinding's Command property is not a DependencyProperty, so you cannot bind something to it.

    See here for a similar problem:

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

    Basically, per the accepted answer to that question, you'll have to use the AttachedCommandBehavior rather than a MouseBinding to achieve what you want. In my opinion that would be the best way if this is something you do a lot.

    Alternatively, if this is the only case in your code that you are doing this I don't think it would hurt to handle the event in code behind and call the view model's command from there. MVVM purists might disagree, but sometimes it's best to do things the simple way rather than tying yourself in knots trying to keep your code behind completely empty!