views:

235

answers:

2

Hi,

I'm currently playing around with a MVVM/Commands and ControlTemplates. What I'm trying to do is quite simple. I want to have a list of e.g. Persons, where the user can trigger an action on each of them. But the event/commandhandler needs to be executed not on the person object e.g. because I want remove it from the list with a button.

So what I did so far was to create a VM that exposes a list of PersonVM's and each of the holds my person object. Then I created a CustomControl with a controltemplate that includes an ItemsControl that displayes my persons.

All the data is displayed nicely, and no problem at all.

Then I tried to add the part that allows the user to remove a person from the list. So I added a button to the datatemplate. Still not a problem.

Next step was to expose a command that is triggered by the button.

The first approach was to use Josh Smiths RelayCommand. So I added one of those to the PersonViewModel and bound it to the button. It works, but the problem is that I need to raise an event (after the command is executed) that the parent vm has to handle. Imho that is not nice, as with more and more commands the code seems messy to me.

So I reworked everything to use RoutedCommand, and tried to add a CommandBinding on a higher level in the control hierarchy. But this is not possible as the ControlTemplate doesn't allow me to call a method on the viewmodel.

So I'm wondering what is the correct approach for that problem? Somehow I believe that I'm on the wrong track, but I don't see where.

tia Martin

A: 

Something I've done that works, if potentially a bit messy, is to use RelativeSource bindings to walk the DataContext (or command binding) back up the logical tree, a la:

Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.MyCommandOnTheViewModel}"
JerKimball
my main model is not exposing the command, my child vm's are exposing it, therefore this doesn't work in my case.
Martin Moser
A: 

When I pass events around using the MVVM pattern, I found Prism’s Event Aggregator extremely useful. It allows you to handle loosely coupled communication.

So generally speaking if I want to pass events like a delete across View Models that do not have an explicit relationship, I will subscribe the one View Model to look for the a specific event aggregation, and then trigger that from the appropriate places.

I am sure there are several variants of this approach, so it may be worth a look?

Mark Pearl
nice approach, but imho more that I need, because imho CommandBindings are exactly designed for my purpose...
Martin Moser