Centering a WPF control

Use a Grid:

  <Grid>  
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*"/>
      <ColumnDefinition Width="Auto"/>
      <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
      <RowDefinition Height="*"/>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <!-- Replace with your UserControl -->
    <Button Content="Foo" Grid.Column="1" Grid.Row="1"/>
  </Grid>

You can dock it inside your DockPanel (if you must have a DockPanel there) to stretch. And, of course, while the above is all markup, you can just as easily create such a grid from code.


I keep running into this problem when trying to center elements on the page. The problem with the StackPanel is that HorizontalAlignment has no effect when the Orientation is Horizontal and VerticalAlignment no effect when Orientation is Vertical. So you keep banging your head trying to set values with no effect. It is not illogical that it works this way but it would be good if this was reported as an error.

The solution I found is to have two imbricated StackPanels one centered horizontally and the other vertically as shown below. Finding the size of the parent is needed to size the intermediate panel otherwise it would be flat and its content hidden - an absolute value would work as well. Although not a panacea itis a bit less verbose than using a grid.

<StackPanel Background="Bisque" Orientation="Vertical" Width="300" Height="300" >
    <StackPanel HorizontalAlignment="Center"  Orientation="Horizontal"
                  Height="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=StackPanel}, Path=ActualHeight}">
        <StackPanel VerticalAlignment="Center" Width="200" Height="60" Background="Blue">
        </StackPanel>
    </StackPanel>
</StackPanel>

Tags:

Wpf

Layout

Fill