0
votes

I have set of nodes and I create image to represent each of them on WPF Form.

        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;
        }

My delegate creates ContextMenu for every image placed on form.

    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;
    }

And then delegate for my submenu Click event

    void submenu_Click(object sender, RoutedEventArgs e)
    {

    }

How can I get acces to my Image when clicking on this Context Menu?

Sender returns MenuItem type

        var item1 = sender;

This returns MainWindow type

        var item2 = this;

Parent returns ContextMenu type

        var item3 = item1.Parent;
1

1 Answers

0
votes

Try setting the DataContext of your ContextMenu to an object that has access to the Image:

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

Or:

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

I'm just guessing here, but you should be able to work which object has access to the Image control.