How to determine the bounds of a WPF control in C # at runtime?

I have a window with several Frame controls and you want to find Bounds / Rectangle controls at runtime. They enter the grid in the window using XAML with the attributes Height / Width / Margin.

The Frame control does not have the Bounds, Rect, Top, or Left properties.

The goal is to check each frame to see if the mouse is inside when other events happen. My current job is to set / clear boolean flags in MouseEnter and MouseLeave handlers, but there should be a better way. This may be obvious because I'm new to C # WPF and .NET.

+4
source share
3 answers

Why don't you just check the IsMouseOver or IsMouseDirectlyOver properties?

+3
source

Despite the fact that others coped with the need, as usual, no one answered the blasted question. I can think of any number of scenarios requiring a boundary definition. For example, HTML display can be performed using IFRAME on the main HTML page, and the ability to place it in accordance with the displayed borders of the panel will allow you to easily integrate it into your interface.

You can determine the origin of the control using the GeneralTransform on Point (0,0) method in the root visual coordinate system, and ActualHeight and ActualWidth are displayed directly.

GeneralTransform gt = TransformToVisual(Application.Current.RootVisual as UIElement); Point offset = gt.Transform(new Point(-1, -1)); myFrame.SetStyleAttribute("width", (ActualWidth + 2).ToString()); myFrame.SetStyleAttribute("height", (ActualHeight + 2).ToString()); myFrame.SetStyleAttribute("left", offset.X.ToString()); myFrame.SetStyleAttribute("top", offset.Y.ToString()); myFrame.SetStyleAttribute("visibility", "visible"); 

In the above example, I converted (-1, -1) and added 2 to the height and width to compensate for the uniform area of ​​the pixel border around the IFRAME - this code is canceled from a working application that uses IFRAME to render the "embedded" HTML when placing the browser.

In addition, there is more than one way to steal a cat, and you can find an interesting VisualTreeHelper for impact testing.

 IEnumerable<UIElement> VisualTreeHelper .FindElementsInHostCoordinates(Point intersectingPoint, UIElement subtree) 

This returns each UIElement below the dot (usually with the mouse). There is an overload that takes Rect instead.

+5
source

you can move the controls using VisualTreeHelper and see if the cursor is in the element using the VisualTreeHelper.HitTest(...) method VisualTreeHelper.HitTest(...)

+1
source

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


All Articles