WPF UserControl is not filling parent container when bound at runtime

wpf

I have a window that has a StackPanel, and the StackPanel has a ContentControl, which gets a UserControl bound to it at run time.

(In MainWindow.xaml)

<StackPanel Margin="6,14,5,6" Grid.Row="1">
  <ContentControl Name="WindowContent" Content="{Binding}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />
</StackPanel>

(In MainWindow.xaml.cs)

WindowContent.Content = new MainWindowView();

I want the UserControl (and it's children) to fill up the space in the StackPanel.

I have checked that all of the Heights and Widths are set to Auto, and Horizontal/VerticalAlignments are set to Stretch, and Horizontal/VerticalContentAlignments are also set to Stretch.

Is there something I'm missing?
This seems like a silly question, but I can't get this to work!

Thanks

Best Answer

The StackPanel container always sizes to its content's minimum size. I believe you want to use a Grid rather than a StackPanel; Grid will attempt to use all available space.

<Grid Margin="6,14,5,6" Grid.Row="1">
   <ContentControl Name="WindowContent" Content="{Binding}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />
</Grid> 

Edit: If you want the same kind of stacking functionality in a Grid, just do something like this:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
</Grid>

That would make 2 minimally sized rows (like a StackPanel) and then a row that took up all the rest of available space.

Related Topic