C# WinForms TextBox垂直对齐

.Net技术 码拜 10年前 (2013-04-21) 2887次浏览 0个评论

需求描述:使用 C# WinForms 实现控件在面板中自由拖动位置,Timer控件对位置校准,使得控件总是在同一行(即Location的Y属性相同),控件包含label、Textbox、combobox,控件大小随内容发生变化,编辑控件值结束时,隐藏控件border,使得同一行在视觉上看不出控件差异。由于textbox在隐藏掉border后,文字和label中文字不在同一直线,有高有低,所以需要Textbox控件在隐藏掉border后内容和label内容同高度。

If you’re turning off AutoSize on a control, it must be a Label, since TextBox doesn’t have an AutoSize property.  The TextAlign property of a Label is of type ContentAligment, so you can set both horizontal and vertical alignment.

For various boring reasons, TextBoxes in windows are intended to auto-adjust their heights to the font used.  To control the heights and vertically center the text, you can quickly create a custom UserControl that you can replace all your textboxes with.

On your user control, set the BorderStyle to Fixed3D and the BackColor to System.Window.  Add a TextBox and set its BorderStyle to None.  In the Resize event for the control, add code that makes the TextBox the same width as the user control’s client area (accounting for the border pixels) and left-aligns it (i.e. textBox1.Left = 0;) and vertically centers it (e.g. textBox1.Top = (this.Height - textBox1.Height) / 2;).

Finally, add to the user control any TextBox-type properties and events you need (probably just Text and TextChanged, I would guess), and wire them up so that they pass through to the TextBox inside your control, like this:

public string Text { get { return textBox1.Text; } set { textBox1.Text = value; } } 

If you wanted to get super-fancy with this, you could even replace your user control’s TextAlign property with one that is actually of type ContentAlignment (like the Label) and then align the inner TextBox to match.

This same approach will work for a ComboBox, although it will look slightly odd.  With the ComboBox, you set its FlatStyle property to Flat – otherwise you deal with it the same as a TextBox.  It will look odd because the dropdown arrow box won’t be quite at the top and bottom of the panel.


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C# WinForms TextBox垂直对齐
喜欢 (0)
分享 (0)