Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine bounds of a WPF control in C# at runtime?

Tags:

c#

.net

wpf

I have a Window with several Frame controls and would like to find the Bounds/Rectangle of the controls at runtime. They go into a grid on the window using XAML with Height/Width/Margin attributes.

The Frame control doesn't have Bounds, Rect, Top or Left properties.

The purpose is to test each frame to see if the mouse is inside when other events occur. My current work around is to set/clear boolean flags in the MouseEnter and MouseLeave handlers but there must be a better way. It could be obvious because I am new to C# WPF and .NET.

like image 292
Ken Avatar asked Dec 22 '22 11:12

Ken


2 Answers

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

like image 132
Thomas Levesque Avatar answered Mar 28 '23 14:03

Thomas Levesque


Although others have met the need, as usual nobody answered the blasted question. I can think of any number of scenarios that require bounds determination. For example, displaying HTML can be done with an IFRAME in the host HTML page, and being able to position it according to the rendered bounds of a panel would allow you to integrate it nicely into your UI.

You can determine the origin of a control using a GeneralTransform on Point(0,0) to the root visual coordinate system, and ActualHeight and ActualWidth are surfaced 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 sample above I have transformed (-1, -1) and added 2 to both height and width to compensate for the single pixel border region around an IFRAME - this code is lifted from a working application that uses an IFRAME to render "embedded" HTML when browser hosted.

Also, there's more than one way to skin a cat and for hit testing you may find VisualTreeHelper interesting.

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

This returns every UIElement under a point (typically from the mouse). There is an overload that takes a Rect instead.

like image 24
Peter Wone Avatar answered Mar 28 '23 15:03

Peter Wone