How to use the IntersectsWith method with a rectangle defined in XAML

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 you need to use the IntersectsWith method , but I can not use it in encoding. When I write in C #:

 MyRectangle.IntersectsWith( 

I get a standard error:

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

I think that since the rectangle in XAML is System.Windows.Shapes.Rectangle , and the method for System.Windows.Rect ? If so, is there a way to “convert” my Rectangle to Rect ?

+4
source share
3 answers

Here is the solution I finally used. For each element I want to check if it intersects with others, I create a Rect containing it. That way I can use the IntersectsWith method.

Example (with rectangles, but you can do it with other numbers, UserControls, ...): XAML

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

WITH#

 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 } 
+2
source

Try

 MyRectangle.RenderedGeometry.Bounds.IntersectsWith(); 
+1
source

you can use VisualTreeHelper.HitTest to check the intersection, remember 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.

+1
source

Source: https://habr.com/ru/post/1491291/


All Articles