MVVM / Commands and Control Templates

I am playing with MVVM / Commands and ControlTemplates now. What I'm trying to do is pretty simple. I want to have a list, for example. Persons where the user can initiate an action for each of them. But the event / command handler should not be executed on the human object, for example. because I want to remove it from the list using the button.

So what I have done so far has been creating a virtual machine that provides a PersonVM list and each of my objects. Then I created a CustomControl with a checklist that includes an ItemsControl element that displays my faces.

All data is displayed well, and no problems.

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

The next step was to open the command, which is launched by the button.

The first approach was to use Josh Smiths RelayCommand. So I added one of them to PersonViewModel and attached it to the button. It works, but the problem is that I need to raise an event (after executing the command) that the parent vm should handle. Imho, which is not very nice, since with a lot of commands the code seems messy for me.

So, I reworked everything to use RoutedCommand, and tried to add CommandBinding to a higher level in the management hierarchy. But this is not possible, since the ControlTemplate does not allow me to call the method on the viewmodel.

, ? - , , , .

+3
2

-, , , , RelativeSource DataContext ( ) , a la:

Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.MyCommandOnTheViewModel}"
+2

MVVM, . .

, , , delete View Models, , View , .

, , ?

0

Source: https://habr.com/ru/post/1726972/


All Articles