This is because the DataContext="{Binding PlacementTarget,...
binding would set the button as MenuItems DataContext
, but that would not add ContextMenu
to the VisualTree of your window and that the ElementName
would not work. A simple workaround for using ElementName
bindings is to add this in window code / UserControl:
NameScope.SetNameScope(contextMenuName, NameScope.GetNameScope(this));
Another solution is to do it -
<ContextMenu DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}"> <MenuItem Command="{Binding DataContext.DoAction}"/> </ContextMenu>
DataContext="{Binding PlacementTarget,...
set the Button (Placementtarget) as the DataContext of your ContextMenu, so you can use the Button DataContext to bind the command.
Update:
You can try to use NameScope.NameScope
Attached Property to set NameScope to XAML, but I'm not sure how you get NameScope parent window without code!
You will need to do something similar to Josh Smith's next article, it provides a way to do this in XAML; but this also includes code (moreover, that one line of code) -
Enable ElementName bindings with ElementSpy
Any specific reason not to use this single line of code?
source share