在运行时绑定时,WPF UserControl不填充父容器

Mic*_*ele 9 wpf

我有一个具有StackPanel的窗口,StackPanel有一个ContentControl,它在运行时获取绑定到它的UserControl.

(在MainWindow.xaml中)

<StackPanel Margin="6,14,5,6" Grid.Row="1">
  <ContentControl Name="WindowContent" Content="{Binding}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

(在MainWindow.xaml.cs中)

WindowContent.Content = new MainWindowView();
Run Code Online (Sandbox Code Playgroud)

我希望UserControl(和它的孩子们)填满StackPanel中的空间.

我已检查所有高度和宽度都设置为"自动","水平/垂直对齐"设置为"拉伸","水平/垂直对齐"也设置为"拉伸".

有什么我想念的吗?这似乎是一个愚蠢的问题,但我不能让这个工作!

谢谢

Ed *_*tes 19

StackPanel容器的大小始终为其内容的最小大小.我相信你想使用Grid而不是StackPanel; 网格将尝试使用所有可用空间.

<Grid Margin="6,14,5,6" Grid.Row="1">
   <ContentControl Name="WindowContent" Content="{Binding}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />
</Grid> 
Run Code Online (Sandbox Code Playgroud)

编辑:如果你想在网格中使用相同类型的堆叠功能,只需执行以下操作:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
</Grid>
Run Code Online (Sandbox Code Playgroud)

这将产生2个最小尺寸的行(如StackPanel),然后是占用所有剩余可用空间的行.