Reputation: 23
In the model I have a observable collection of objects. With an ItemsControl (and UserControl) I display these elements (shapes).
Now I want to do hittesting on the parent canvas.
For example when I execute this code:
HitTestResult result = VisualTreeHelper.HitTest(allContent, new Point(70, 340));
I get a HitTestResult
, but I want to get the object in the model representing this "clicked" shape.
Is there a possibility of getting the object?
Upvotes: 1
Views: 434
Reputation: 2336
To get to the DataContext that is bound to the ListBoxItem in question, I do this:
HitTestResult result = VisualTreeHelper.HitTest( itemsContainer, position ) ;
FrameworkElement currentElement = result.VisualHit as FrameworkElement ;
while( (currentElement is ListBoxItem)==false
&& currentElement!=itemsControlElement
&& currentElement!=null)
{
currentElement = VisualTreeHelper.GetParent(currentElement) as FrameworkElement ;
}
if( currentElement != null )
{
object dataSource = currentElement.DataContext ;
}
If you switch the stack walk to look for your UserControl instead of a ListBoxItem and change the itemsControlElement to be whatever your ItemsControl container is, it should prevent runaway walks of the visual tree.
Upvotes: 2