我有一组节点,我创建图像以在 WPF 表单上表示它们中的每一个。
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri("pack://application:,,,/WpfApplication1;component/Resources/Node.png", UriKind.Absolute);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
foreach (var item in nodeList)
{
Image newImage = new Image();
newImage.Margin = new Thickness(item.Position.X , item.Position.Y , 0, 0);
newImage.Source = src;
Canvas1.Children.Add(newImage);
newImage.MouseRightButtonDown += newImage_MouseRightButtonDown;
}
我的代表为放置在表单上的每个图像创建 ContextMenu。
void newImage_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
ContextMenu menu = new ContextMenu();
int index = Canvas1.Children.IndexOf((Image)sender);
MenuItem addExistingLink = new MenuItem();
addExistingLink.Header = "Add Existing Link";
addExistingLink.Click += submenu_Click;
MenuItem addNewLink = new MenuItem();
addNewLink.Header = "Add New Link";
addNewLink.Click += submenu_Click;
menu.Items.Add(addExistingLink);
menu.Items.Add(addNewLink);
menu.IsOpen = true;
}
然后委托我的子菜单点击事件
void submenu_Click(object sender, RoutedEventArgs e)
{
}
单击此上下文菜单时如何访问我的图像?
发件人返回 MenuItem 类型
var item1 = sender;
这将返回 MainWindow 类型
var item2 = this;
父级返回 ContextMenu 类型
var item3 = item1.Parent;