I can`t seem to get this right click popup menu to work.
Since learning more and more about C# and WPF if anyone else is looking for an answer regarding this. the answer is simple.
Your going about it the wrong way. If you need to use a "Behaviour" over and over again and your using either a MVVM style code (or you think you are because its probably not quite there yet) You need to use what they call an Attached Property.
Simply Put.
Handle Everything in your Attached Property PropertyMetadata Event Handler.
<Style TargetType="MenuItem">
<Setter Property="Properties:ControlMenuItem.InvokeClick" Value="{Binding RelativeSource={RelativeSource Self}}"/>
</Style>
ContextMenu
ist not part the the Visual Tree and so FindAncestory
data binding won't work.
You could set the DataContext
on the ContextMenu
explicitly though.
e.g. you could create an instance of your ViewModel / DataContext directly in XAML if that's an option.
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<ContextMenu.DataContext>
<local:MyViewModel/>
</ContextMenu.DataContext>
<MenuItem Command="{Binding Path=CommandPopupClick}"
CommandParameter="{Binding Path=SelectedItem}"
Header="Delete" />
<Separator />
<MenuItem Command="{Binding Path=CommandPopupClick}"
CommandParameter="{Binding Path=SelectedItem}"
Header="Properties" />
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
Or get it from a StaticResource
.
<Window.Resources>
<local:MyViewModel x:Key="ctx"/>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu DataContext="{StaticResource ctx}">
<MenuItem Command="{Binding Path=CommandPopupClick}"
CommandParameter="{Binding Path=SelectedItem}"
Header="Delete" />
....
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
You can't use a RelativeSource Binding
to access the TreeView.DataContext
from the ContextMenu
because it is not in the main UI visual tree. This is a very well documented problem and the solution is to pass the DataContext
object through to the ContextMenu
using the ContextMeny.PlacementTarget
property and the Tag
property on the object that has the Contextmenu
applied to it.
Having already written and re-written about this many times, nowadays, I much prefer to request that you read my answers to the ContextMenu.PlacementTarget is not getting set, no idea why and Add context menu in datagrid, how to get the select Item value questions here on Stack Overflow for full explanations and code examples. If you need further help, just search the internet for 'WPF ContextMenu DataContext' or something similar and you should find dozens of tutorials on this exact topic.