I have an entity view model. As there can be many entities in the UI, I have used a DataTemplate for representing an entity view model. This data template is used by the container control’s ItemTemplate property to render the entities.
Please note this is not the conventional ListView/ListBox control. It is a Graph control with the edges and nodes being represented by the data templates.
This said, each of the nodes are of different type and when the user right clicks, the context menu of the template is getting bound to a collection provided by the view model. Following code is working fine:
<DataTemplate DataType="{x:Type model:Person}">
<Border Style="{StaticResource NodeBorderStyle}" MinWidth="200">
<Border.ContextMenu>
<ContextMenu ItemsSource="{Binding ContextOperations}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding PlacementTarget.DataContext.HandleContextOperationCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
<Setter Property="CommandParameter" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Header}"/>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</Border.ContextMenu>
....................
</Border >
</DataTemplate>
This has a limitation, the ContextOperations (an ObservableCollection) property has to be populated when the view model gets initialized.
There may be numerous nodes and hence storing context menu items for all the nodes at loading time can be a matter of huge memory.
I want that when the user right clicks the entity (the template), the ContextOperations property of the viewmodel gets populated and then the context menu gets rendered.
This DataTemplate is kept in a resource file.
Any guidance would be appreciated.
Thank you.
regards,
Handle the MouseRightButtonUp event on you datatemplate border and create the context menu runtime like this:
and remove the definition of contextmenu from the XAML.