user2847238
user2847238

Reputation: 169

Canvas child identification

I have a node class with Point property called Location. I create several object of this class and then I put them on the generic list. In my app every node is represended by the Image (node location == image location).

To render images I iterate my nodelist and add images to Canvas on my WPF main window. Basically first item on my list is the first child of my Canvas.

When I change location of my node then when rendering Image automatically changes aswell. But if I want to move Image using MouseMove event I have no idea how to acces specific element from my nodelist. How do I know which element is which?

Upvotes: 2

Views: 1514

Answers (2)

Clemens
Clemens

Reputation: 128042

Since you add Images to the Canvas in the same order as the nodes in your nodelist, you may simply get the Canvas child index and access the node by that index:

private void canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    var element = canvas.InputHitTest(e.GetPosition(canvas)) as UIElement;

    if (element != null)
    {
        int index = canvas.Children.IndexOf(element);
        node hitNode = nodelist[index];
    }
}

Upvotes: 3

dev hedgehog
dev hedgehog

Reputation: 8791

Click/drag/hover with your mouse over a specific image and transform its (0,0) points against canvas.

Point relativePoint = image.TransformToAncestor(myCanvas)
                              .Transform(new Point(0, 0));

Then run through your list and find the image with location same as relativePoint.

Thats how you find the one which captured your mouse cursor.

Also this is a nice post to read about transforming in wpf.

http://msdn.microsoft.com/en-us/library/ms750596.aspx

Upvotes: 1

Related Questions