Search code examples
wpftext-alignmentdockpanel

How to get text-alignment and stretch in the dockpanel correct?


In a xaml DataTemplate I have

<DockPanel >
    <StackPanel DockPanel.Dock="Right" Orientation="Vertical">
        <Button />
        <Button />
    </StackPanel>
    <Grid VerticalAlignment="Stretch/Center">
        <TextBlock HorizontalAlignment="Stretch"
                   TextAlignment="Right"
                   Text="{Binding ...}"
                   VerticalAlignment="Stretch"
                   DockPanel.Dock="Right"/>
    </Grid>
</DockPanel>

The dockpanel is horizontal, i.e. stackpanel is to the right, the grid to the left.

I need the two buttons to stretch each to 50% of the vertical space of height of the dockpanel. How do I do it?

A schematic picture of want I try to achieve. The controls are meant to stretch to the borders as much as possible. enter image description here

I need the textblock to stretch to 100% of the vertical space of height of the dockpanel and it's text to be vertically centered. It doesn't work bc. in the case of Strech I get the 100% space but the text is vertically topped and in the case of Center the textblock is not stretched.


Solution

  • A TextBlock cannot both "stretch to 100% of the vertical space" and also be vertically centered. It's just text after all.

    You should be able to get rid of the StackPanel and replace the DockPanel with a 2x2 Grid. Something like this:

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="2*" />
            <ColumnDefinition Width="1*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Button Grid.Column="1" Content="Button1" />
        <Button Grid.Column="1" Content="Button2" Grid.Row="1" />
        <Grid Grid.RowSpan="2">
            <TextBlock Grid.RowSpan="2"
                       TextAlignment="Right"
                       Text="Text..."
                       VerticalAlignment="Center"
                       HorizontalAlignment="Center"/>
        </Grid>
    </Grid>
    

    enter image description here