Connecting mouse events with ViewModel via MouseBinding

logeeks picture logeeks · Feb 29, 2012 · Viewed 10.5k times · Source

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 Leftbuttondown event to know when a user clicks on the telerik control. I tried using the MouseBinding technique to bind the Leftbuttondown to the event handler in the viewmodel. I am not sure about what is the signature for the event handler. I read from somewhere that the command to bind should be of tyepe ICommand and the Execute method takes only one parameter. The signature for the Leftbuttondown event is like

 public void SelectItem(object o, EventArgs e)

How can i pass the extra argument to the Execute?

I have done the following coding in xaml

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

How should i define the SelectedItem in the ViewModel?

will giving Command="SelectedItem" work? or should i add Binding clause here?

Thanks in advance

Answer

Pongsathon.keng picture Pongsathon.keng · Feb 29, 2012

First thing you need some kind of RelayCommand which implement System.Windows.Input.ICommand. This will help you on Binding.

XAML

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

ViewModel

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