Stefan Valianu
Stefan Valianu

Reputation: 1410

How do I get the dimensions of a WPF element at run-time without specifying them at compile-time

The problem?

<UI:PanelBrowser Margin="12,27,12,32"></UI:PanelBrowser>

WPF is ridiculous in that not manually specifying properties (Such as Width and Height) in this case causes them to have the values Doulbe.NaN. The problem is that I need to know this number. I'm not going to manually set a width and height in the XAML because that stops it from resizing.

Given the above piece of XAML (this object is a simple subclass of the Border control), how can I get the values of the Width and Height properties at run-time?

Edit :

Wow, I feel ridiculous. I read about ActualWidth and ActualHeight, but they were consistently returning 0 and 0 for me. The reason is that I was testing for these properties in the constructor of the Framework Element, before they were actually initialized. Hope this helps someone who runs into the same issue and testing fallacies. :)

Upvotes: 5

Views: 8031

Answers (4)

FrankLinTw
FrankLinTw

Reputation: 71

Use VisualTreeHelper.GetDescendantBounds(Visual Reference), and it return Rect.
Then Check the height of the Rect.
Ex)

Rect bounds = VisualTreeHelper.GetDescendantBounds(element);
double height = bounds.height;

OR
Use UIElement.Measure(Size size), it will assign the Size into DesiredSize.
Ex)

myElement.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));  
double height = myElement.DesiredSize.Height;

Upvotes: 0

Umair A.
Umair A.

Reputation: 6873

You can use elements' ActualWidth and ActualHeight properties to get the values of the width and height when they were drawn.

Upvotes: 1

naacal
naacal

Reputation: 620

The WPF FrameworkElement class provides two DependencyProperties for that purpose: FrameworkElement.ActualWidth and FrameworkElement.ActualHeight will get the rendered width and height at run-time.

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564821

Try using the FrameworkElement.ActualWidth and ActualHeight properties, instead.

Upvotes: 16

Related Questions