Vertically aligning Labels and TextBlocks at Top in XAML
Asked Answered
S

3

10

How can I vertically align a Label and TextBlock at Top so that their first lines of text line up?

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition />
    </Grid.RowDefinitions>
    <Label Grid.Column="0" VerticalAlignment="Top">Some Label:</Label>
    <TextBlock Grid.Column="0" VerticalAlignment="Top">Some text<TextBlock>
</Grid>

The above code gives me this:

Vertically misaligned Label and TextBlock text http://img156.imageshack.us/img156/4940/labeltextblock.png

Sympathetic answered 8/7, 2009 at 18:18 Comment(2)
The question's code is quite broken. The Label and TextBlock are both in column 0, row 0, and appear on top of each other. The TextBlock "closing" tag is actually a 2nd TextBlock opening tag so I'm guessing the code wasn't copied from a working example. (The image for this old question is also broken.) Tested 2021-07-17.Nidify
The edit queue is full, but corrected question code: ``` <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition /> </Grid.RowDefinitions> <Label Grid.Column="0" VerticalAlignment="Top">A</Label> <TextBlock Grid.Column="1" VerticalAlignment="Top">B</TextBlock> </Grid> ```Nidify
W
21

The extra space around the label comes from the Padding property. To remove the space, you can explicitly set the Padding property to "0" directly on the Label, or, of course, set it via a Style.

Wardship answered 8/7, 2009 at 18:37 Comment(3)
It seems that a Label's Padding is set to 5 by default, and a TextBlock's is set to 0. Thanks for the answer.Sympathetic
The problem begins when the FontSize is different between the two controls.Brynhild
Thanks for unveiling one of the mysteries of WPF to meSulfaguanidine
B
1
<TextBlock>
<InlineUIContainer BaselineAlignment="Top"><Label Content="Label"/></InlineUIContainer>
<InlineUIContainer BaselineAlignment="Top"><TextBlock>TextBlock Content</TextBlock>                 </InlineUIContainer>
</TextBlock>

HTH.

Bondon answered 28/3, 2013 at 7:47 Comment(0)
B
0

Here is a workaround: Align bottoms of text in controls.

I posted a connection: https://connect.microsoft.com/WPF/feedback/ViewFeedback.aspx?FeedbackID=523432, please vote.

Brynhild answered 19/1, 2010 at 4:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.