C# 单击上下文菜单WPF时获取对父级的访问权限
我有一组节点,我创建了一个图像来表示WPF表单上的每个节点C# 单击上下文菜单WPF时获取对父级的访问权限,c#,wpf,contextmenu,C#,Wpf,Contextmenu,我有一组节点,我创建了一个图像来表示WPF表单上的每个节点 BitmapImage src = new BitmapImage(); src.BeginInit(); src.UriSource = new Uri("pack://application:,,,/WpfApplication1;component/Resources/Node.png", UriKind.Absolute); src.CacheOption = Bi
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;
}
我的代理为表单上放置的每个图像创建上下文菜单
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;
这将返回主窗口类型
var item2 = this;
父级返回上下文菜单类型
var item3 = item1.Parent;
尝试将
上下文菜单的DataContext
设置为可以访问图像的对象:
ContextMenu menu = new ContextMenu();
menu.DataContext = this;
或:
我在这里只是猜测,但您应该能够确定哪个对象可以访问图像控件。菜单.DataContext=((图像)发送方)
而不是menu.DataContext=this代码>谢谢更新。。。那么,这解决了您的问题吗?我必须再添加一行var item1=((MenuItem)sender)代码>图像项2=((图像)项1)代码>请将此代码添加到问题的末尾,以便将来的用户可以轻松找到您的解决方案。非常感谢。
ContextMenu menu = new ContextMenu();
menu.DataContext = this.DataContext;