#269 – Automatically Sizing a Window to Fit Its Contents

You normally set the width and height of a WPF Window by setting its Width and Height properties directly.

<Window Width="400" Height="300" >

At runtime, this sets the starting window size.

If you want the window to automatically size to fit its contents, you can set the SizeToContent property.  By default, this property has a value of Manual, indicating that the Width and Height properties will dictate the window’s size.  (Ignoring the effect of min/max properties).

Setting SizeToContent to Height will force the window to adjust its height to fit the contents.

<Window Width="400" Height="300" SizeToContent="Height">

Setting SizeToContent to Width will force the window to adjust its width to fit the contents.

<Window Width="400" Height="300" SizeToContent="Width">


And setting it to WidthAndHeight will tell the window to adjust both dimensions.

<Window Width="400" Height="300" SizeToContent="Width">

Advertisements