views:

1245

answers:

1

Hi everyone,

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.

A: 

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>
Jalfp
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
I think you could change the code so that when you call your command you give in parameter a Tuple<EventArgs, object> instead of simply giving the CommandParameter objec
Jalfp
Could you show me an example please.
Tri Q
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.
Jalfp