How to use IntersectsWith method with a rectangle defined in XAML
Asked Answered
R

3

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?

Rob answered 14/7, 2013 at 0:10 Comment(0)
R
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
}
Rob answered 16/7, 2013 at 22:28 Comment(0)
P
1

Try it

MyRectangle.RenderedGeometry.Bounds.IntersectsWith();
Pires answered 14/7, 2013 at 4:21 Comment(1)
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".Playpen
H
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.

Hydrolyte answered 14/7, 2013 at 6:26 Comment(2)
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 :)Playpen
@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 feelingsHydrolyte

© 2022 - 2024 — McMap. All rights reserved.