Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronizing parent height to child height in WPF

Tags:

wpf

xaml

I'm developping with VS 2015 and WPF a mask designer, in which i can drag, move and resize controls. One of These controls is a Label which has a TextBlock as Content.

This looks in my XAMl like that:

<Label Background="AliceBlue" HorizontalAlignment="Left" Margin="10,5,0,0" VerticalAlignment="Top">
    <TextBlock TextWrapping="Wrap" Height="Auto">Label</TextBlock>
</Label>

For the TextBlock i have set TextWrapping to "Wrap" and Height to "Auto". When i try to resize the height of the Label at it's allowed minimum, the content of the TextBlock shall still be completely visible. I tried this with a TextBlock and it worked. But when i try it with a Label implementing a TextBlock it doesn't work, the content of the TextBlock isn't completely visible anymore.

How can i synchronize the parent's height to the child's height?

Thanks in advance! Patrick

like image 880
Patrick Pirzer Avatar asked Apr 11 '16 10:04

Patrick Pirzer


2 Answers

You can use the Name of parent and bind its 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>

Edit

   <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>
like image 93
Ghassen Avatar answered Sep 16 '22 19:09

Ghassen


@Ghassen's answer is basically correct. If you want to bind the parent to the child then reverse the answer above. The reversed code is shown below.

<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>
like image 21
wilson2610 Avatar answered Sep 19 '22 19:09

wilson2610