【问题标题】:How to keep Font in inherited TextBox?如何将字体保留在继承的文本框中?
【发布时间】:2010-11-16 08:39:11
【问题描述】:

我正在使用以下代码来获取未绘制边框的 TextBox:

public partial class CustomTextBox : TextBox
{
    public CustomTextBox()
    {
        InitializeComponent();
        SetStyle(ControlStyles.UserPaint, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        int borderWidth = 1;

        ControlPaint.DrawBorder(e.Graphics, e.ClipRectangle,
            Color.Transparent, borderWidth, ButtonBorderStyle.Solid,
            Color.Transparent, borderWidth, ButtonBorderStyle.Solid,
            Color.Transparent, borderWidth, ButtonBorderStyle.Solid,
            Color.Transparent, borderWidth, ButtonBorderStyle.Solid);
    }
}

我似乎错过了 OnPaint() 内部的某些内容,因为我的字体不再是文本框的默认字体(也许我必须覆盖另一个事件)。

检查 CustomTextBox.Font 属性时,它会显示默认的“Microsoft SansSerif in 8,25”,但在我的 textBox 中输入文本时,字体肯定看起来更大更粗。

希望你能帮助我!

问候,

创新

[编辑]

我应该提到,如果我不覆盖 OnPaint,我的 CustomTextBox 的字体是正确的。仅当覆盖 OnPaint 时,我的字体不正确(输入文本时字体更大并且似乎是粗体)。 所以我认为我必须做一些事情来正确初始化 OnPaint 内的字体(但 ATM 我不知道该怎么做)。

【问题讨论】:

  • 不要在构造函数中将 UserPaint 设置为 true,而是在 OnControlCreated() 中设置。这将解决字体问题。

标签: c# .net winforms user-controls


【解决方案1】:

如果尚未创建文本框的句柄,则不要调用 SetStyle,它永远不会更改为“大粗体”字体:

if (IsHandleCreated)
{
     SetStyle(ControlStyles.UserPaint, true);
}

【讨论】:

  • 很好的答案,这是我想弄清楚的缺失部分。在构造函数中设置UserPaint 样式会破坏它,但在OnControlCreated() 中调用它会起作用。
【解决方案2】:

如果您没有明确设置 TextBox 的字体,它会从其父级和祖先那里获取字体,因此如果 TextBox 在 Panel 上,它会从该 Panel 或父 Form 获取其字体。

【讨论】:

  • Parent 有相同的字体“Microsoft SansSerif 8,25”,但打字时我不认为是这个字体。
【解决方案3】:

两个选项供您查看... 在我的基类中,我强制使用只读字体定义...与其他控件类似,因此具有该类的其他开发人员无法更改它 --- PERIOD。

[ReadOnly(true)]
public override Font Font
{
    get
    {
        return new Font("Courier New", 12F, FontStyle.Regular, GraphicsUnit.Point);
    }
}

第二个选项,其实我并没有在表单的序列化过程中使用。我不能相信,也不记得我在这个论坛的其他地方找到了什么,但也可能有所帮助。显然,通过隐藏序列化可见性,它不会强制每个单独控件的属性(在这种情况下,应用您的字体)[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]

HTH

【讨论】:

  • 将这两种方法添加到我的 CustomTextBox 类中,但均未成功。无论如何,谢谢。
【解决方案4】:

根据this answer,在文本框上使用SetStyle 总是会弄乱绘画。

但是...有什么理由不能简单地将其设置为 BorderStyleNone

如果需要,您甚至可以修改BorderStyle,使其默认值为None,如下所示:

using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace MyControls
{
  // Apply ToolboxBitmap attribute here
  public class CustomTextBox : TextBox
  {
    public CustomTextBox()
    {
      BorderStyle = BorderStyle.None;
    }

    [DefaultValue(typeof(System.Windows.Forms.BorderStyle),"None")]
    public new BorderStyle BorderStyle
    {
      get { return base.BorderStyle; }
      set { base.BorderStyle = value; }
    }
  }
}

【讨论】:

    猜你喜欢
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    相关资源
    最近更新 更多