Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Aligning the base line of a Label and its TextBox

Let's say I have a simple TextBox next to a Label:

<StackPanel>     <StackPanel Orientation="Horizontal">         <Label Margin="3">MyLabel</Label>         <TextBox Margin="3" Width="100">MyText</TextBox>     </StackPanel>     ... </StackPanel> 

This yields the following result:

result

As you can see, the base lines of MyLabel and MyText are not aligned, which looks ugly. Of course, I could start playing around with the margins until they match up, but since this is such a common requirement I'm sure that WPF provides a much easier and more elegant solution, which I just haven't found yet...

like image 953
Heinzi Avatar asked Jun 14 '10 17:06

Heinzi


People also ask

How do I align a TextBox and label?

We specify the margin-bottom of our <div> element. Then, we set the display of the <label> element to "inline-block" and give a fixed width. After that, set the text-align property to "right", and the labels will be aligned with the inputs on the right side.

How do I center text in a label in WPF?

If you want to center each line, use a TextBlock instead, and set TextAlignment="Center" .

How do I center a TextBox in WPF?

VerticalAlignment = "Center" and padding You can reach the text within a WPF-TextBox with the combination VerticalAlignment and Padding. Like VerticalAlignment = "Center" Padding = "5" Padding causes the text field to become larger and adapt to the surrounding element.

What is content alignment in WPF?

This article focuses on the content alignment of elements. Content Alignment. The content of content controls in WPF is dealt using various properties. These two properties are HorizontalContentAlignment and VerticalContentAlignment. These properties are defined in the System.


1 Answers

This behaviour is, I think, caused by the fact that the TextBox defaults to a vertical alignment of Stretch, which causes it to fill the available space and have the extra couple of pixels under the text. If you use this instead:

<StackPanel>     <StackPanel Orientation="Horizontal">         <Label >MyLabel</Label>         <TextBox VerticalAlignment="Center" Width="100">MyText</TextBox>     </StackPanel> </StackPanel> 

... you should see a cleaner result.

like image 113
Dan Puzey Avatar answered Oct 03 '22 00:10

Dan Puzey