Reputation: 13516
I am implementing an explorer-type view: on the left is a TreeView and on the right is a details view / editor view of the item selected on the left.
The TreeView contains different types of 'leaf' objects. I have defined HierarchialDataTemplates to define how the objects are presented and which context menu should be presented. The MenuItems have Commands which are bound to the view-model.
What I am struggling with is where to implement the Command handlers. The straight-forward place would be in the 'leaf' view-models but they don't know anything about the 'explorer' view-model and how to open the details/editor view.
The simplest solution would be to bind the leaf context menu to the explorer view-model as this is where the action is best executed.
How is this normally handled? Are there any 'well-known' patterns?
Upvotes: 0
Views: 193
Reputation: 13516
Just found the answer to this question - Bind to parent DataContext within DataTemplate - which put me on the right track.
The UserControl
get a name and the command binding references this - Source={x:Reference uc}}
.
<UserControl x:Class="View.AdminWorkstationView" Name="uc">
<UserControl.Resources>
<DataTemplate DataType="{x:Type vm:RequiredDeviceViewModel}">
<DockPanel>
<DockPanel.ContextMenu>
<ContextMenu>
<MenuItem Command="{Binding DataContext.EditDeviceCommand, Source={x:Reference uc}}"
CommandParameter="{Binding}"
Header="Edit device" />
</ContextMenu>
</DockPanel.ContextMenu>
</DockPanel>
</DataTemplate>
</UserControl.Resources>
Upvotes: 1