WPF MVVM Routed Events

Tri Q Tran picture Tri Q Tran · Oct 19, 2009 · Viewed 8k times · Source

There are a lot of discussions about M-V-VM and Command binding (RelayCommand) but not a lot has been covered on Routed Events binding to a handler in a M-V-VM pattern. I want to find what is the best approach.

Here is an example of RoutedEvent binding using a custom event and a bound event handler to the VM.

<Navigation:LeftNavigation x:Name="_leftNav" Margin="3"
            BindingHelper:EventHelper.RoutedEvent="Events:Customer.SelectionChanged"
            BindingHelper:EventHelper.EventHandler="{Binding SelectionChanged}" />

In my Vm, I would have an event handler similar to this.

public void SelectionChanged(object sender, CustomerSelectionChangedArgs e)
{
    // Do something
}

This is only a concept taken from many examples from command binding. How would I get this to work for routed events.

Answer

japf picture japf · Oct 20, 2009

You can check out this article that where the author implements a similar syntax:

<Border Background="Yellow" Width="350" Margin="0,0,10,0" Height="35" CornerRadius="2" x:Name="test">
  <local:CommandBehaviorCollection.Behaviors>
    <local:BehaviorBinding Event="MouseLeftButtonDown" Action="{Binding DoSomething}" CommandParameter="An Action on MouseLeftButtonDown"/>
    <local:BehaviorBinding Event="MouseRightButtonDown" Command="{Binding SomeCommand}" CommandParameter="A Command on MouseRightButtonDown"/>
  </local:CommandBehaviorCollection.Behaviors>
  <TextBlock Text="MouseDown on this border to execute the command"/>
</Border>