How can I add a ContextMenu to a ItemsControl, where:
Firstly, just check your parameter values for null
:
return parameter == null ? false : _canExecuteMethod((T)parameter);
Secondly, this is the old ContextMenu.DataContext
problem: The ContextMenu
is displayed in a different visual tree to the rest of the UI. It therefore has no access to a DataContext
from the main UI visual tree. Because of this, we have to use a little trick to pass it through to the other visual tree. Our connection between the two is the ContextMenu.PlacementTarget property.
From the linked page, this property
Gets or sets the UIElement relative to which the ContextMenu is positioned when it opens.
We can use the Tag
property of the ContextMenu.PlacementTarget
object to pass the DataContext
. Basically, just set the Tag
property on the object that you will set the ContextMenu
on. Try something like this:
<ItemsControl x:Name="myItems" ItemsSource="{Binding MyItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding MyText}" Tag="{Binding DataContext,
RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
ContextMenu="{StaticResource ItemContextMenu}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
...
<ContextMenu x:Key="ItemContextMenu" ItemsSource="{Binding ContextMenuItems}"
ItemContainerStyle="{StaticResource CommandMenuItemStyle}"
DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}"/>
That's it. Now the UI elements declared in the ContextMenu
will have access to whatever object you data bind to the Tag
property. There's absolutely no need for EventSetter
s to use a ContextMenu
... it's quite simple if you know how.
It is a known bug in wpf and framework 4.0 try using 4.5 framework. https://connect.microsoft.com/VisualStudio/feedback/details/619658/wpf-virtualized-control-disconnecteditem-reference-when-datacontext-switch