Home >

Why is the Width/Height Property for many Elements ‘NaN’ in WPF?

14. March 2007

Developers new to WPF are sometimes a little confused when the Width and Height properties of elements report as ‘NaN’ (Not a Number) in code, when these very same elements are clearly visible and do have a width and height. What’s going on?

The short answer is you can interpret ‘NaN’ to mean “not set”. The Width and Height properties of Buttons, TextBoxes and most other controls are inherited from the FrameworkElement superclass. These normal .NET properties in turn backs on to a DependencyProperty (the WidthProperty in the case of Width) that has been registered for FrameworkElement in the class constructor with a default value of ‘NaN’. Until you set that WidthProperty to something, or set the Width .NET property in code or Xaml the Width will stay as ‘NaN’. If you wish to know what the on-screen size for an object is you should instead consult the ActualWidth and ActualHeight properties, which always reflects the actual width and height of the object on screen. These properties are sometimes a little hard to find given the number of public properties and methods on many objects in WPF.  

Comments are closed