views:

363

answers:

2
+1  Q: 

Hit Testing in WPF

Hi, I have an Ellipse on a Canvas and I'm doing a Hit Testing on it. Every time I click the stroke of the Ellipse, the test pass. If I click in the middle of the Ellipse, the test fails. This is good ! After I fill the ellipse like this: myEllipse.Fill = new SolidColorBrush(Colors.Blue); the test pass also when I click in the middle of the Ellipse. How can I disable this ? (even when Ellipse is Filled, the test will fail when I click in the middle) Thanks !

+1  A: 

If you do your own hit testing (see Hit Testing in the Visual Layer for details on how to do this), you should be able to check the IntersectionDetail of the GeometryHitTestResult is IntersectionDetail.Intersects, and not IntersectionDetail.FullyContains.

Reed Copsey
+1  A: 

Sounds like a good and clean solution ! However, I don't understand how to implement it. I tried to retrieve the IntersectionDetail like it is done here, but when I click the Ellipse I got InvalidCastException saying "Unable to cast object of type 'System.Windows.Media.PointHitTestResult' to type 'System.Windows.Media.GeometryHitTestResult'". Here are some parts of my code:

void OnMouseLeftButtonDown(Object sender, MouseButtonEventArgs e) 
{
   ...
   VisualTreeHelper.HitTest(canvas, null, new HitTestResultCallback(MyHitTestResult), new PointHitTestParameters(e.GetPosition((UIElement)sender)));
   ...
}

public HitTestResultBehavior MyHitTestResult(HitTestResult result)
{
   IntersectionDetail intersectionDetail = ((GeometryHitTestResult)result).IntersectionDetail; // Got InvalidCastException here !
   ...
}

Please help to understand where is the problem.