views:

131

answers:

3

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...

+4  A: 

What do you think?

alt text

<StackPanel Orientation="Horizontal">
        <Label Margin="3" VerticalContentAlignment="Center">MyLabel</Label>
        <TextBox Margin="3" VerticalContentAlignment="Center" Width="100">MyText</TextBox>
 </StackPanel>
Markust
+1, looks nice, thanks. I've accepted Dan's answer as correct, though, since his solution keeps the TextBox's box at it's "natural" height instead of stretching it.
Heinzi
+3  A: 

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.

Dan Puzey
+1  A: 

I achieved that look in Kaxaml with:

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