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
?
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
}
Try it
MyRectangle.RenderedGeometry.Bounds.IntersectsWith();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With