Setting DataContext for ContextMenu in ItemsControl.DataTemplate

后端 未结 1 1610
迷失自我
迷失自我 2021-01-06 01:05

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

相关标签:
1条回答
  • 2021-01-06 01:58

    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.

    0 讨论(0)
提交回复
热议问题