WPF:对齐标签的基线及其文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3039254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:51:08  来源:igfitidea点击:

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

wpflayoutalignmentbaseline

提问by Heinzi

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

假设我在标签旁边有一个简单的 TextBox:

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

可以看到,MyLabel和MyText的基线没有对齐,看起来很难看。当然,我可以开始使用边距直到它们匹配,但由于这是一个如此常见的要求,我确信 WPF 提供了一个更简单、更优雅的解决方案,我只是还没有找到......

回答by Dan Puzey

This behaviour is, I think, caused by the fact that the TextBoxdefaults 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:

我认为,这种行为是由于TextBox默认为 的垂直对齐方式造成的Stretch,这会导致它填充可用空间并在文本下方有额外的几个像素。如果您改用它:

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

... you should see a cleaner result.

...你应该看到一个更清晰的结果。

回答by Marcote

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>

回答by user7116

I achieved that look in Kaxaml with:

我在 Kaxaml 中实现了这种外观:

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

回答by Kristian

I know that this is an old answer, but for here's an example for those who seek another way, where you don't need to rely on a fixed textbox width:

我知道这是一个旧答案,但对于那些寻求另一种方式的人来说,这是一个示例,您不需要依赖固定的文本框宽度:

Instead of StackPanel, use a DockPanel and .Dock.

使用 DockPanel 和.Dock.

This proves to be very handy when used inside a Grid.

当在 Grid 中使用时,这被证明是非常方便的。

<DockPanel Grid.Column="2" Grid.Row="2">
     <Label Content="SomeTitle:" DockPanel.Dock="Left"></Label>
     <TextBox x:Name="SomeValueTextBox" VerticalAlignment="Center" DockPanel.Dock="Right"></TextBox>
</DockPanel>

Result

结果