Reputation: 1312
I have a ContentControl with a Grid in it. There is a Template for ContextMenu of each ListBoxItem. The ContextMenu Looks like this:
<ContentControl.Resources>
<ContextMenu x:Key="SimpleDataObjectContextMenu" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Create" Command="{Binding AddRelation}" CommandParameter="..Name..of..caller.."/>
<MenuItem Header="Delete" Command="{Binding DeleteRelation}" CommandParameter="..Name..of..caller.."//>
</ContextMenu>
</ContentControl.Resources>
The Grid looks like this:
<Grid>
<Rectangle x:Name="LeftRectangle" Width="5" Height="5" Fill="Black" Margin="5" ContextMenu="{StaticResource SimpleDataObjectContextMenu}"/>
<TextBlock Text="{Binding Model.Name}"/>
<Rectangle x:Name="RightRectangle" Width="5" Height="5" Fill="Black" Margin="5" ContextMenu="{StaticResource SimpleDataObjectContextMenu}"/>
</Grid>
I want to submit from the "LeftRectangle" and "RightRectangle" (which are using the own ContextMenu Template "SimpleDataObjectContextMenu") the x:Name to the "SimpleDataObjectContextMenu", so that I can submit this Name as CommandParameter in the Template.
Instead of ..Name..of..caller.. for example I want to send "LeftRectangle", if the ContextMenu was opened on the left rectangle...
Any idea, how can I realize this?
Upvotes: 0
Views: 464
Reputation: 1482
You can bind command parameter like this
CommandParameter="{Binding Path=Menu.UIElement, RelativeSource={RelativeSource Self}
and in code behind you can cast the parameter with Rectangle like this
var rectangle = parameter as Rectangle ;
if(rectangle != null)
{
var name = rectangle.Name;
}
Upvotes: 0
Reputation: 2031
Remove DataContext
binding from your ContextMenu
:
<ContextMenu x:Key="SimpleDataObjectContextMenu" >
<MenuItem Header="Create" Command="{Binding AddRelation}" CommandParameter="{Binding Parent.PlacementTarget.Name, RelativeSource={RelativeSource Self}}"/>
<MenuItem Header="Delete" Command="{Binding DeleteRelation}" CommandParameter="{Binding Parent.PlacementTarget.Name, RelativeSource={RelativeSource Self}}"/>
</ContextMenu>
Upvotes: 1