6

I have this rectangle in XAML :

<Rectangle x:Name="MyRectangle" Height="300" Width="300"></Rectangle>

I want to check if it intersects with another rectangle. In this question on SO, they say that one have to use the IntersectsWith method. But I'm unable to use it in code-behind. When I write in C# :

MyRectangle.IntersectsWith(

I get the standard error:

"System.Windows.Shapes.Rectangle does not contain a definition for 'IntersectsWith' and no extension method [...]"

I think that's because the rectangle in XAML is a System.Windows.Shapes.Rectangle, and the method is for System.Windows.Rect? If so, is there a way to "transform" my Rectangle into a Rect?

Community
  • 1
  • 1
Michaël Polla
  • 3,511
  • 3
  • 23
  • 37

3 Answers3

4

Here's the solution I finally used. For each element I want to test if it intersects with others, I create a Rect containing it. Thus, I can use the IntersectsWith method.

Example (with rectangles, but you can do this with other figures, UserControls,...) : XAML

<Canvas>
    <Rectangle x:Name="Rectangle1" Height="100" Width="100"/>
    <Rectangle x:Name="Rectangle2" Height="100" Width="100" Canvas.Left="50"/>
</Canvas>

C#

Rect rect1 = new Rect(Canvas.GetLeft(Rectangle1), Canvas.GetTop(Rectangle1), Rectangle1.Width, Rectangle1.Height);
Rect rect2 = new Rect(Canvas.GetLeft(Rectangle2), Canvas.GetTop(Rectangle2), Rectangle2.Width, Rectangle2.Height);
if(rect1.IntersectsWith(r2))
{
    // The two elements overlap
}
Michaël Polla
  • 3,511
  • 3
  • 23
  • 37
1

Try it

MyRectangle.RenderedGeometry.Bounds.IntersectsWith();
Nitesh
  • 7,261
  • 3
  • 30
  • 25
  • Hi ! Thanks for you reply. I tried your suggestion but couldn't make it work. I overlapped two rectangles on a canvas, but when I write : if(Rect1.RenderedGeometry.Bounds.IntersectsWith(Rect2.RenderedGeometry.Bounds)), the condition isn't "true". – Michaël Polla Jul 16 '13 at 20:17
1

you can use VisualTreeHelper.HitTest to test intersection don`t forget to set GeometryHitTestParameters

Windows Presentation Foundation (WPF) hit testing only considers the filled area of a geometry during a hit test. If you create a point Geometry, the hit test would not intersect anything because a point has no area.

makc
  • 2,569
  • 1
  • 18
  • 28
  • Hi ! thanks for your help. I was almost able to find a working solution, especially with the example provided with GeometryHitTestParameters documentation, but in the meantime I found another solution that was easier for me to write and understand :) – Michaël Polla Jul 16 '13 at 20:38
  • 1
    @MichaëlPolla welcome :), there is no single right solution, if IntersectsWith solves the problem then you are on the right path :) you can accept your own answer ;) no hard feelings – makc Jul 18 '13 at 10:31