2

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.

Tri Q Tran
  • 5,500
  • 2
  • 37
  • 58

1 Answers1

2

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>
japf
  • 6,598
  • 3
  • 33
  • 30
  • Thank you Jalfp, I have tried this technique myself. The problem I found with this approach is that the Command/Action executes with only the parameters pass in by CommandParameter, but what about the event args coming from the event that triggered it. Is there any solution to that or am I just completely off in the wrong path? – Tri Q Tran Oct 21 '09 at 00:11
  • I think you could change the code so that when you call your command you give in parameter a Tuple instead of simply giving the CommandParameter objec – japf Oct 21 '09 at 20:32
  • Actually I just took a look at the source code and this is not as easy as I thought. A delegate is dynamically created to match the signature of the EventHandler and I couldn't find a way to grab the EventArgs from here... If you don't use a fully customizable approach and create an attached property for the event you want it should be easier. – japf Oct 22 '09 at 16:05
  • I know this is an old post but that's why I'm responding. Does ANYONE have this code because it doesn't exist on the linked website anymore. – Philip Vaughn Jul 08 '20 at 18:08