单击ContextMenu WPF时访问父级

时间:2013-10-28 10:27:36

标签: 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 = 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;
    }

然后委托我的子菜单Click事件

    void submenu_Click(object sender, RoutedEventArgs e)
    {

    }

如何在单击此上下文菜单时访问我的图像?

发件人返回MenuItem类型

        var item1 = sender;

返回MainWindow类型

        var item2 = this;

Parent返回ContextMenu类型

        var item3 = item1.Parent;

1 个答案:

答案 0 :(得分:0)

尝试将DataContext的{​​{1}}设置为有权访问ContextMenu的对象:

Image

或者:

ContextMenu menu = new ContextMenu();
menu.DataContext = this;

我只是在这里猜测,但您应该能够使用哪个对象可以访问ContextMenu menu = new ContextMenu(); menu.DataContext = this.DataContext; 控件。