Search code examples
c#wpfsize

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. :)


Solution

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