Associating WPF ContextMenu MenuItem with UserControl Property vs ViewModel Property

I am trying to understand what is happening with ContextMenu. I know that this appears as a separate window with a separate visual tree, so we cannot use relative binding to bind a command open as a property of a user control. For example, the following does not work :

<MenuItem Command="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=TestCommand}" Header="Test" /> 

But if you set the data context of the user control to a view model that provides the command as a property, the following will work:

 <MenuItem Command="{Binding TestCommand}" Header="Test" /> 

I do not understand how ContextMenu inherits the value of a DataContext if it is not part of the visual tree. I expect both of these examples to behave the same way (i.e. both work or both fail).

+3
source share
1 answer

The second binding works because of the so-called "inheritance context". You can read about it here: http://blogs.msdn.com/b/nickkramer/archive/2006/08/18/705116.aspx . This is mainly a special case where some properties inherit the data context of the owner object. So, for example, the inheritance context always works on properties of type Freezable (another interesting article about Freezables: http://drwpf.com/blog/category/freezables/ ).

Actually, the article says that the inheritance context does not work on ContextMenu, but in version 4 they added it, so it really works now, as you showed it in your example.

+3
source

Source: https://habr.com/ru/post/1334071/


All Articles