tags:

views:

229

answers:

3

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.

+1  A: 

you can traverse your controls by VisualTreeHelper and see if the cursor in the element by VisualTreeHelper.HitTest(...) method

ArsenMkrt
This also worked, but IsMouseOver seemed more direct.
Ken
+1  A: 

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

Thomas Levesque
Thanks - I missed that property somehow.
Ken
A: 

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.

Peter Wone