How calculate intersection of UI element with its parent?

Neo 351 Reputation points
2023-05-03T08:12:57.3733333+00:00

I get the following answer form AI assistant Claude:

In UWP, you can calculate the intersection of a UI element with its parent like this: Get the Rect of the child element relative to the parent:

Rect childRect = childElement.TransformToVisual(parentElement)
Rect childRect = childElement.TransformToVisual(parentElement).TransformBounds(new Rect(0, 0, childElement.ActualWidth, childElement.ActualHeight));

Get the Rect of the parent element:

Rect parentRect = new Rect(0, 0, parentElement.ActualWidth, parentElement.ActualHeight); 

Use Rect.Intersect to get the intersection:

Rect intersection = Rect.Intersect(childRect, parentRect);

The intersection Rect will have a non-zero width and height if the elements intersect. You can check it like this:

if (intersection.Width > 0 && intersection.Height > 0) 
{
Elements intersect!
}
else 
{
No intersection 
}

I am not sure it's the most conside and elegant way. Is there any builtin method to achieve same purpose?

Universal Windows Platform (UWP)
{count} votes