Auto resize window content in WPF

Mohit Deshpande picture Mohit Deshpande · Jan 20, 2010 · Viewed 29.1k times · Source

When debugging my WPF programs I have noticed that when the window is the set size, the contols look just fine. But when the window is maximized, the content is positioned at the same place as if window has not resized. I want it so that the content and window resize proportionately. How can I do this? Sorry if it is a noobish question, but I'm kinda new in the WPF era.


The XAML code is not completely ready yet but here is some of elements:

<DockPanel>
    <StackPanel DockPanel.Dock="Left">
    ...
    </StackPanel>

    <TabControl DockPanel.Dock="Right">
    ...
    </TabControl>

    <ListView>
    ...
    </ListView>
</DockPanel>

Answer

David Veeneman picture David Veeneman · Jan 20, 2010

Usually, this is because dimension values are set statically, rather than dynamically. Here's the static approach:

<RowDefinition x:Name="NavigatorRow" Height="120"/>
<RowDefinition x:Name="TaskPanelRow" Height="80"/>

Both rows will have fixed heights, and they won't resize with the window.

Here is the dynamic approach:

<RowDefinition x:Name="NavigatorRow" Height="1*"/> 
<RowDefinition x:Name="TaskPanelRow" Height="80"/>

The bottom row still has a fixed height of 80, but the top row will expand to fill whatever space is available. In other words, the rows will resize with the window. Columns work the same way.

If I had three rows, I could do this:

<RowDefinition x:Name="NavigatorRow" Height="1*"/>
<RowDefinition x:Name="CalendarRow" Height="2*"/>
<RowDefinition x:Name="TaskPanelRow" Height="80"/>

The Navigator Row and the Calendar Row will share the available space, with the Calendar Row taking twice the height of the Navigator Row. You get the idea.

So, it's not the container you use, but how you size that container. The one exception, as noted above, is the StackPanel, which does not scale. Use a Grid instead, since it does scale.