<Rectangle Fill="Purple" Width="200" Height="100" ContextMenuOpening="AddItemToCm">
<Rectangle.ContextMenu>
<ContextMenu>
<MenuItem Header="Item1"/>
<MenuItem Header="Item2"/>
<MenuItem Header="Item3"/>
</ContextMenu>
</Rectangle.ContextMenu>
</Rectangle>
private void AddItemToCm(object sender, ContextMenuEventArgs e)
{
//check if Item4 is already there, this will probably run more than once
var fe = e.Source as FrameworkElement;
var cm = fe.ContextMenu;
if (cm.Items.Cast<MenuItem>().Any(mi => (string) mi.Header == "Item4"))
{
return;
}
var mi4 = new MenuItem {Header = "Item4"};
fe.ContextMenu.Items.Add(mi4);
}
网友评论