How can I get the size of an autosized WPF Window?

4.4k Views Asked by At

I have a Window that is autosized around it's content. For an animation I'd need it's width and height. ActualWidth is always the max width of the window, Width and Height properties say NaN.

3

There are 3 best solutions below

1
On

You can use the Window's UpdateLayout()-Method to have ActualWidth and ActualHeight validated.

1
On

ActualWidth/ActualHeight will give you the actual sizes of the window - given by the layout system, which is based on the actual rendering of the window. These should be the sizes you are looking for. However, there might be a slight delay in the calculation as it is based on rendering, so if they are wrong I guess they aren't calculated yet - and you got a race condition going on.. You can read more about this in links above, where there are some important notes on when the actual sizes are calculated - and hence - why they can be delayed.

Width/Height are requested sizes, and if not set explicitly they will hold their default values, which is Double.NaN.

1
On

Whenever possible you should use a ScaleTransform instead of changing Height and Width values when animating a size change. Not only can it help with performance, but it also gets around issues like this since instead of setting a specific size value which you may not know, the scale values are specified as percentages.