You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

移除边框后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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 23:36:38