Reputation: 7728
I have a ContextMenu defined in the following way:
<ContextMenu>
<MenuItem Header="Add to">
<MenuItem Header="Test1" Click="ItemClicked" />
<MenuItem Header="Test2" Click="ItemClicked" />
</MenuItem>
<MenuItem Header="Remove from All" />
</ContextMenu>
But in the ItemClicked function how would I get a reference to the parent ContextMenu??
For the first level items (e.g. "Remove from All") I can do something like the following:
var mi = sender as MenuItem;
if (mi != null)
{
var cm = mi.Parent as ContextMenu;
if (cm != null)
{
var lb = cm.PlacementTarget as ListBox;
if (lb != null)
{
// Do Stuff
}
}
}
But this doesn't work for submenu MenuItems because their Parent is null...
Upvotes: 1
Views: 3075
Reputation: 6583
try using LogicalTreeHelper.GetParent()
which will return the Parent Element
LogicalTreeHelper.GetParent(e.Source as DependencyObject);
Upvotes: 1