C# 对齐文本框和标签文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1170315/
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
Align TextBox and Label text
提问by Clement Herreman
I'm designing a UI, and I found myself itching my head : how can I align a TextBox text and a label text, which are side by side.
我正在设计一个用户界面,我发现自己很头疼:如何将并排的 TextBox 文本和标签文本对齐。
In design mode, it's easy, you move one with your mouse, a purple line appears and voila ! the alignment is good, but mine are code generated, so how can i align their contents ?
在设计模式下,这很容易,你用鼠标移动一个,出现一条紫色的线,瞧!对齐很好,但我的是代码生成的,所以我如何对齐它们的内容?
Thank you !
谢谢 !
Edit: Layout is something I can't use (I don't make the rules, my boss do..)
编辑:布局是我不能使用的东西(我不制定规则,我的老板做..)
采纳答案by Roman Starkov
I like to use the FlowLayoutPanel
(instead of the TableLayoutPanel
) for this purpose because you don't need to fiddle with columns. Rememberto remove both the Top and the Bottom anchors on every control to make them vertically centered, and set FlowLayoutControl.AutoSize = true and AutoSizeMode = GrowAndShrink.
我喜欢为此目的使用FlowLayoutPanel
(而不是TableLayoutPanel
),因为您不需要摆弄列。请记住删除每个控件上的顶部和底部锚点,使它们垂直居中,并设置 FlowLayoutControl.AutoSize = true 和 AutoSizeMode = GrowAndShrink。
Edit: regarding your restriction that "Layout is something I can't use": so you want instead to access the purple text baseline snapline position programmatically, at runtime? This is possible, but it's unlikely to be faster than layouts because only the designerfor the control knows where it is, so you will have to create designers for all controls you need this for.
编辑:关于您对“布局是我不能使用的东西”的限制:所以您想在运行时以编程方式访问紫色文本基线对齐线位置?这是可能的,但它不太可能比布局更快,因为只有控件的设计者知道它在哪里,因此您必须为需要它的所有控件创建设计器。
This questionhas some code that can be used as a starting point, but as I said, it's probably not the right approach either given the performance constraints.
这个问题有一些代码可以用作起点,但正如我所说,考虑到性能限制,这可能不是正确的方法。
回答by Henk Holterman
Take a look at the TableLayoutPanel. Still not so easy to get the baseline match but by vertically centering the label and setting the Rows to AutoSize you will get something that is ordered and flexible.
看一下 TableLayoutPanel。获得基线匹配仍然不是那么容易,但通过垂直居中标签并将行设置为 AutoSize,您将获得有序且灵活的内容。
回答by Matt Jacobsen
then use the X, Y, Width, Height properties of each control (inherited from Control).
然后使用每个控件的 X、Y、宽度、高度属性(继承自 Control)。
int padding = 5;
textbox.Y = label.Y;
textbox.X = label.Width + padding