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
WPF: Aligning the base line of a Label and its TextBox
提问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:
这会产生以下结果:
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 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:
我认为,这种行为是由于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
回答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>