In WPF, the equivalent of DockStyle.Fill WinForms:
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
This is the default value for almost controls, so you don’t have to do anything to have a WPF control to populate the parent container . They do it automatically. This is true for all containers that do not squeeze their children to a minimum size.
Common mistakes
Now I will explain some common errors that prevent HorizontalAlignment="Stretch" VerticalAlignment="Stretch" from working HorizontalAlignment="Stretch" VerticalAlignment="Stretch" as expected.
1. Explicit height or width
One common mistake is to explicitly determine the width or height for the control. Therefore, if you have this:
<Grid> <Button Content="Why am I not filling the window?" Width="200" Height="20" /> ... </Grid>
Just remove the Width and Height attributes:
<Grid> <Button Content="Ahhh... problem solved" /> ... </Grid>
2. Contains control of compression panels to a minimum size
Another common mistake is that the containing panel compresses your control as much as it does. For example, a vertical StackPanel will always compress its contents vertically as little as possible:
<StackPanel> <Button Content="Why am I squished flat?" /> </StackPanel>
Switch to another panel, and you will be fine:
<DockPanel> <Button Content="I am no longer squished." /> </DockPanel>
In addition, any row or column with a height of "Auto" likewise compresses its contents in that direction.
Some examples of containers that do not squeeze their children:
- ContentControls never compresses its children (including Border, Button, CheckBox, ScrollViewer and many others).
- Single row and column grid
- Grid with rows and columns of size * *
- DockPanel does not compress its last child
- TabControl does not compress its content
Some examples of containers that compress their children:
- Stackpanel shrinks in orientation
- A grid with a type row or Auto column in that direction
- DockPanel compresses all but its last child towards the dock
- TabControl compresses its title (which is displayed on the tab)
3. Explicit height or width below
It's amazing how many times I see a Grid or DockPanel with explicit height and width, for example:
<Grid Width="200" Height="100"> <Button Content="I am unnecessarily constrainted by my containing panel" /> </Grid>
In general, you never want to give any panel explicit heights or widths. My first step in diagnosing layout problems is to remove every explicit height or width that I can find.
4. SizeToContent window when it should not be
When you use SizeToContent, your content will be compressed to a minimum size. In many applications, this is very useful and is the right choice. But if your content does not have a “natural” size, you probably want to omit SizeToContent.