Bind to parent DataContext within DataTemplate

若如初见. 提交于 2019-11-30 09:49:59

If you are on .NET 4 there indeed is a more elegant solution:

<UserControl Name="uc" ...>
<!-- ... -->
    <MenuItem Header="Remove"
              Command="{Binding DataContext.RemoveItem,
                                Source={x:Reference uc}}"/>

(This requires that the template stays in the Resources, otherwise there will be a cyclical dependency error)

Menus are not drawn in the same Visual Tree as your Controls, which is why the RelativeSource binding does not work

You need to bind to the PlacementTarget of your ContextMenu to access the main Visual Tree

<MenuItem Header="Remove" 
          Command="{Binding PlacementTarget.DataContext.RemoveItem, 
              RelativeSource={RelativeSource FindAncestor, 
              AncestorType={x:Type ContextMenu}}}" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!