views:

146

answers:

2

Building my baseclasses for user interface controls is getting there. I have command buttons derived with custom font assignment and put on a form, all is fine... However, identical code for the read-only property Font of a textbox is NOT recognized properly on the same form. It is ONLY taking the setting of the FORM and disregarding its own Font declaration.

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

The Font property is an ambient property. If it was never assigned, it automatically matches the Font property of the container control. You never assigned it.

Do it like this:

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; }
    }
}
Hans Passant
Sorry, didn't work. I pasted your code verbatim in and dragged that into my form. Even before the control was allowed to be added it came back withFailed to create componeent "myTextbox" ...System.NullReferenceException: Object reference not set to an instance of an object.
DRapp
Also, the code for my Command button was verbatim on the "Font" issue, and IT works perfectly... no extra property setting, and just immediately returns the font object via the GETter...
DRapp
Got it... see my self answer, but yours HELPED...
DRapp
A: 

With a help from "nobugz" (Thanks), I found this same failure when doing a ComboBox too. My result was the following...

My getter

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

However, in nobugz response, something wasn't working quite right with the compiler, so in the constructor of the class

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