如何在inheritance的TextBox中保留Font?
我正在使用以下代码来获取未绘制其边框的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()内部的东西,因为我的Font不再是textBox的默认字体(也许我必须覆盖另一个事件)。
当检查CustomTextBox.Font属性时,它向我显示默认的“Microsoft SansSerif in 8,25”,但在我的textBox中键入文本时,Font肯定看起来更大更粗。
希望你能帮我!
问候,
INNO
[编辑]
我应该提一下,如果我不重写OnPaint,我的CustomTextBox的字体是正确的。 只有当覆盖OnPaint我的字体不正确时(键入文本时字体更大,似乎是粗体)。 所以我认为我必须做一些事情来在OnPaint中正确初始化字体(但ATM我不知道如何做到这一点)。
如果尚未创建文本框的句柄,请不要调用SetStyle,并且它不会更改为“大粗体”字体:
if (IsHandleCreated) { SetStyle(ControlStyles.UserPaint, true); }
如果您没有明确地设置TextBox的字体,它将从其父级和祖先获取其字体,因此如果TextBox位于Panel上,它将从该Panel获取其字体,或从父Form获取。
你可以看两个选项…在我的基类中,我强制使用只读字体定义…与其他控件类似,所以其他类开发人员无法更改它— PERIOD。
[ReadOnly(true)] public override Font Font { get { return new Font("Courier New", 12F, FontStyle.Regular, GraphicsUnit.Point); } }
第二个选项,我实际上没有使用是在表单序列化过程中。 我不能信任,也不记得我在这个论坛的其他地方找到了什么,但也可能有帮助。 显然,通过隐藏序列化可见性,它不会强制每个单独控件的属性(在这种情况下,适用于您的字体) [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
HTH
根据这个答案 ,在文本框上使用SetStyle
总会弄乱这幅画。
但是……有什么理由不能简单地将它的BorderStyle
设置为None
?
如果需要,您甚至可以修改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; } } } }