移除边框后WinForms控件文本垂直对齐异常问题
问题描述
我有一个最终继承自TextBox的Control控件,保留边框时文本垂直对齐显示正常:
但我通过以下代码移除边框后,文本对齐出现偏移:
public partial class MyReadonlyDataField : TextBox { private void InitializeComponent() { this.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Appearance.BorderAlpha = Infragistics.Win.Alpha.Transparent; this.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.Height = 19; } }
无边框时的偏移效果:
请问该如何解决此问题?
解决方案
调整内边距(Padding):
移除边框后,TextBox默认内边距会发生变化,手动设置Padding抵消偏移:this.Padding = new Padding(0, 1, 0, 0); // 按需微调Top/Bottom值通过修改上下内边距,让文本回到垂直居中位置。
重写OnPaint自定义绘制:
若内边距调整无效,重写OnPaint直接控制文本绘制位置:protected override void OnPaint(PaintEventArgs e) { e.Graphics.Clear(this.BackColor); StringFormat sf = new StringFormat { Alignment = StringAlignment.Far, // 匹配右对齐设置 LineAlignment = StringAlignment.Center }; Rectangle textRect = new Rectangle(0, 0, ClientSize.Width, ClientSize.Height); e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), textRect, sf); }建议同时设置
this.DoubleBuffered = true避免绘制闪烁。调整Infragistics控件专属属性:
由于用到了Infragistics的Appearance.BorderAlpha,可尝试调整控件自带的Appearance.Padding:this.Appearance.Padding = new Padding(0, 1, 0, 0);微调控件高度:
TextBox的高度默认关联字体+边框尺寸,移除边框后可尝试修改Height值(比如从19改为17/20),找到让文本居中的合适高度。
内容的提问来源于stack exchange,提问作者juergen d
相关产品推荐
相关产品推荐

