I have custom control that is being used in data template for an ItemsControl. I want to put a ContextMenu on each item and have it call the UserControl\'s View Model to pr
ContextMenu doesn't lie in same Visual Tree
as that of ItemsControl. Hence RelativeSource and ElementName won't work in Binding because they traverse Visual tree to found the source.
If you are using WPF 4.0 or higher you can use x:Reference
markup extension to bind with ItemsControl dataContext.
Set x:Name
on ItemsControl and bind using x:Reference
like this:
<ItemsControl x:Name="itemsControl">
....
<MenuItem Command="{Binding DataContext.ClearAlarmsCommand,
Source={x:Reference itemsControl}}"
Header="Clear All" />
....
</ItemControl>
Also you can use Freezable BindingProxy
approach if you are targeting version lower than WPF 4.0. Refer to my answer over here for the approach.