Search code examples
silverlightimagecanvasvisualtreehelper

SIlverlight: Can't find Image on Canvas


In my Canvas, I have an image object. I haven't set a source in it, but it has coordinates and a size. The tag is:

<Image Canvas.Top="50" Canvas.Left="20" Height="68" Width="110" HorizontalAlignment="Left" Name="image1" Stretch="Fill" VerticalAlignment="Top" />

Here's the problem: When I move the mouse over it, I want to find it. With this code:

VisualTreeHelper.FindElementsInHostCoordinates(point, Application.Current.RootVisual)

It won't find the image unless a source is set. If no source is set, then the image isn't returned. Does anyone know why? This is causing me problems. I have some drag/drop code and I'm looking to drop something on that Image control, but I need to know when the mouse is over it.

I know there are other ways I could do it (such as placing something else in that location, like a grid or something and detecting that), but that's not going to work. I can think of several ways that will work, but they're far less elegant.

If I could get the above to return my image, that would definitely be ideal.


Solution

  • In your code you had Point point = e.GetPosition(_canvas); This gets the MousePosition co-ordinates in relation to the canvas, but your second line VisualHelper.FindElementsInHostCoordinates(point,Application.Current.RootVisual) is searching in relation to the whole page. You need to change one or the other so they in relation to the same control. I would just change to VisualHelper.FindElementsInHostCoordinates(point,_canvas)