tags:

views:

35

answers:

1
+1  Q: 

[XAML] hittesting

Hi,

In the model i have a observable collection of objects. With a itemscontrol (and usercontrol) i display these elements (shapes). Now i want to do hittesting on the parrent 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 posibility to get the object?

Thnx

A: 

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.

Ben Von Handorf