0

我有一组节点,我创建图像以在 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;
4

1 回答 1

0

尝试将DataContext您的设置为ContextMenu有权访问的对象Image

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

或者:

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

我只是在这里猜测,但您应该能够确定哪个对象可以访问Image控件。

于 2013-10-28T10:47:48.153 回答