在WPF中将父高同步到子高

Pat*_*zer 3 wpf xaml

我正在使用VS 2015和WPF开发遮罩设计器,可以在其中拖动,移动控件和调整控件的大小。这些控件之一是具有TextBlock作为内容的Label。

在我的XAMl中看起来像这样:

<Label Background="AliceBlue" HorizontalAlignment="Left" Margin="10,5,0,0" VerticalAlignment="Top">
    <TextBlock TextWrapping="Wrap" Height="Auto">Label</TextBlock>
</Label>
Run Code Online (Sandbox Code Playgroud)

对于TextBlock,我已将TextWrapping设置为“ Wrap”,将Height设置为“ Auto”。当我尝试将Label的高度调整为允许的最小值时,TextBlock的内容仍将完全可见。我用TextBlock尝试了一下,它起作用了。但是,当我尝试使用实现TextBlock的Label进行尝试时,它不起作用,TextBlock的内容不再完全可见。

如何将父母的身高与孩子的身高同步?

提前致谢!帕特里克

小智 6

@Ghassen 的回答基本上是正确的。如果您想将父级绑定到子级,请反转上面的答案。反向代码如下所示。

<Label x:Name="ParentLabel" Height="{Binding ElementName=ChildBlock, Path=ActualHeight}" Width="{Binding ElementName=ChildBlock, Path=ActualWidth}"  Background="Blue">
      <TextBlock x:Name="ChildBlock" Height="100" Width="100" Background="Green"></TextBlock>
</Label>
Run Code Online (Sandbox Code Playgroud)


Gha*_*sen 5

您可以使用父级的名称并绑定其ActualHeight

<Label x:Name="parentElementName" Background="AliceBlue" HorizontalAlignment="Left" Margin="10,5,0,0" VerticalAlignment="Top">
        <TextBlock TextWrapping="Wrap"  Height="{Binding ActualHeight, ElementName=parentElementName}">Label</TextBlock>
</Label>
Run Code Online (Sandbox Code Playgroud)

编辑

   <Label x:Name="parentElementName" Background="AliceBlue" Height="{Binding ActualHeight, ElementName=Child}"HorizontalAlignment="Left" Margin="10,5,0,0" VerticalAlignment="Top">
            <TextBlock  x:Name="Child" TextWrapping="Wrap"  Height="Auto">Label</TextBlock>
    </Label>
Run Code Online (Sandbox Code Playgroud)