【问题标题】:Subclassed Textbox readonly font not recognized on form表单上无法识别子类文本框只读字体
【发布时间】:2009-03-24 02:31:28
【问题描述】:

为用户界面控件构建我的基类即将实现。我有通过自定义字体分配派生的命令按钮并放在表单上,​​一切都很好......但是,在同一表单上无法正确识别文本框的只读属性字体的相同代码。它只接受 FORM 的设置,而忽略了自己的 Font 声明。

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

【问题讨论】:

    标签: c# winforms fonts class


    【解决方案1】:

    Font 属性是环境属性。如果它从未被分配,它会自动匹配容器控件的 Font 属性。你从来没有分配过它。

    这样做:

    public class MyTextbox : TextBox {
        Font mFont;
        public MyTextbox() {
            base.Font = mFont = new Font("Courier New", 12f, FontStyle.Regular, GraphicsUnit.Point);
        }
    
        [ReadOnly(true)]
        public override Font Font {
            get { return mFont; }
        }
    }
    

    【讨论】:

    • 对不起,没用。我将您的代码逐字粘贴到我的表单中。即使在允许添加控件之前,它也会返回 Failed to create component "myTextbox" ...System.NullReferenceException: Object reference not set to an instance of an object.
    • 另外,我的命令按钮的代码在“字体”问题上是逐字逐句的,它工作得很好......没有额外的属性设置,只是立即通过 GETter 返回字体对象......
    【解决方案2】:

    在“nobugz”(谢谢)的帮助下,我在做 ComboBox 时也发现了同样的失败。我的结果如下...

    我的吸气剂

    get { return new Font( ... ); }
    

    但是,在 nobugz 响应中,编译器的某些内容不太正常,因此在类的构造函数中

    clas MyTextbox...
    {
       public MyTextbox()
       {
          // it defaults itself from its own read-only font "new" object instance and works
          base.Font = Font;
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-05
      • 2012-08-06
      • 2020-03-02
      • 2012-08-22
      相关资源
      最近更新 更多