Wpf – Handling wpf control events in the ViewModel

event-handlingmvvmwpf

Is there an alternative to Attached Command Behaviour for handling events like DataGrid's MouseDoubleClick event, or TextBox's LostFocus event in the ViewModel ?

e.g., View::

    <Window ........
            DataContext=".......">


        <TextBox LostFocus="{Binding Command1}" />

        <! -- or -->

        <WpfToolkit:DataGrid MouseDoubleClick="{Binding Command2}".../>

    </Window>

ViewModel::

public class MyViewModel
{
   public ICommand Command1
   {
      .......
   }


   public ICommand Command2
   {
      .......
   }
}

Best Solution

I have created a BindEvent class which I use in the view to bind an event to a method in the datacontext. I use it like this:

public MyView()
{
  InitializeComponent();
  Loaded += new RoutedEventHandler(BindEvent.Create("ControlLoaded"));
}

I can add the source here later if you are interested.

Related Question