How to make controls resize in WPF equivalently to Windows Form's anchor/dock properties? How to make controls resize in WPF equivalently to Windows Form's anchor/dock properties? wpf wpf

How to make controls resize in WPF equivalently to Windows Form's anchor/dock properties?


This has caused me grief as well and AlexK helped me see the light. The trick is NOT to set the Height and Width.... Set these to AUTO and use the MARGIN to set the size. Set the HORIZONTALALIGNMENT and VERTICALALIGNMENT to STRETCH and then the anchor functionality works.


The control needs to stretch, that's all there should be to it:

<MyControl HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>

Stretch replaces setting anchors to both respective sides.

For help on panels see this overview. Also see the documentation of the layout system.

Most controls automatically stretch, if you have a DataGrid it should stretch too, this example contains a DataGrid and a TextBlock which shows its size:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">    <Grid>        <Grid.RowDefinitions>            <RowDefinition />            <RowDefinition Height="Auto"/>        </Grid.RowDefinitions>        <DataGrid Name="grid">            <DataGrid.Columns>                <DataGridTextColumn Binding="{Binding Name}" Header="Name"/>                <DataGridTextColumn Binding="{Binding Tag}" Header="Occupation"/>            </DataGrid.Columns>            <FrameworkElement Name="Skeet" Tag="Programmer"/>            <FrameworkElement Name="Gravell" Tag="Programmer"/>            <FrameworkElement Name="Steve" Tag="Coffee Getter"/>        </DataGrid>        <TextBlock Grid.Row="1">            <TextBlock.Text>                <MultiBinding StringFormat="{}{0}, {1}">                    <Binding ElementName="grid" Path="ActualWidth"/>                    <Binding ElementName="grid" Path="ActualHeight"/>                </MultiBinding>            </TextBlock.Text>        </TextBlock>    </Grid></Window>

If you size the window down the DataGrid's ScrollBars should appear.


I assume the control that does not resize is your custom control.

  • Use DockPanel as a container.
  • Remove explicit Width and Height properties from your control.

If you work in VS2008, then this causes inconvenience, because you control would collapse to the minimal size when viewed in the designer.

Expressions Blend and starting from VS2010 both respect designer namespace, so you can specify design time only control size.

For that add the following to your control:

<UserControl ...    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"     mc:Ignorable="d"    d:DesignWidth="WWW" d:DesignHeight="HHH">    ....</UserControl>

d:DesignWidth and d:DesignHeight specify the design time width and height.