Automatically resize a Window to fit content in WPF

SizeToContent property of Window indicates whether a window will automatically size itself to fit the size of its content. This value is a type of SizeToContent enumeration that has four values – Manual, Width, Height, and WidthAndHeight.

  • When SizeToContent is set to WidthAndHeight, the values of Height or Width properties have no effect.
  • When SizeToContent is set to Height, setting Height does not change the height of the window.
  • When SizeToContent is set to Width, setting Width does not change the width of the window.
  • When SizeToContent ise set to Manual, the size of window is determined by other properties including Width, Height, MaxWidth, MaxHeight, MinWidth, and MinHeight.

The following code snippet sets the SizeToContent to WidthAndHeight.

<Window x:Class="WindowSample.MainWindow"



        Title="WPF Window Sample"

        Width="300" Height="200" Left="500" Top="500"

        SizeToContent="WidthAndHeight" >

This example shows how to set the SizeToContent property to specify how a window resizes to fit its content at run-time. Choose one of them ;)

// Manually alter window height and width
this.SizeToContent = SizeToContent.Manual;

// Automatically resize width relative to content
this.SizeToContent = SizeToContent.Width;

// Automatically resize height relative to content
this.SizeToContent = SizeToContent.Height;

// Automatically resize height and width relative to content
this.SizeToContent = SizeToContent.WidthAndHeight;

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now