动态添加的 UserControl 不会调整到父大小

Dynamically added UserControl does not adjust to parent size

我有一个 UserControl,它将在运行时加载到 ContentControl 中。 即使我没有设置宽度和高度,用户控件也不会根据父控件调整其大小。我想念什么?

        <ContentControl x:Name="MainContentControl" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" >
        <Label  Background="LightGray" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" >Sample control </Label>
    </ContentControl>

ContentControl 中的示例控件( label )工作正常,并根据 ContentControl 的大小变化进行扩展。

当我现在用 UserControl 替换 Label 时,Usercontrol 的大小最大尺寸是其中标签的位置

这里是用户控件

<UserControl x:Class="test.testUserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <Label Content="Label" HorizontalAlignment="Left" Margin="235,200,0,0" VerticalAlignment="Top"/>
</Grid>

您正在使用 HorizontalAlignmentVerticalAlignment 告诉 WPF "draw this control with only the size it needs, then align it in the parent container according to these rules".

因此,您的标签将被绘制成所需的确切大小,然后放置在左上角。

如果您的代码的顶部部分使用了 HorizontalContentAlignmentVerticalContentAlignement,这意味着 "align the content inside this control like this"

因此 HorizontalContentAlignment="Center" VerticalContentAlignment="Center" 将根据父容器的规则绘制 Label(听起来像您的情况 Stretch),然后 Label 中的内容将位于中间。

因此,要么将您的 Horizonta/VerticalAlignment 属性更改为 Horizontal/VerticalContentAlignment,要么设置它们的值 Stretch