Reputation: 1433
According to the MSDN,
The
Font
property is an ambient property that if not set, is retrieved from the parent control.
So I create a TextBox
inside a Form
. Make sure to delete the TextBox1.Font
property, and when compiled, the textbox shows the parent's font as expected. Curiously, when handling HandleCreated
event (or when checking in the control constructor when inherited) and checking TextBox1.Font
it is not null
.
Moreover, I change Form1.Font
to a bigger font (from the default Microsoft Sans Serif, 8.25pt to Microsoft Sans Serif, 9.75pt), go to the TextBox1.Font
property and delete the value. When compiled, the textbox shows the bigger parent's font as expected. But on HandleCreated
event, TextBox1.Font == null
is false
(you won't be able to delete the control font property, but at least it won't be bold) and more interestingly the TextBox1.Font
is not 9.75pt size (the parents font size) but the Windows default 8.25pt.
What am I missing?
Just to complement with code
private void CtlTextBox_HandleCreated(object sender, EventArgs e)
{
if (this.Font == null)
{
MessageBox.Show("null");
}
else
{
MessageBox.Show(this.Font.Size.ToString());
}
}
So maybe the parent's font is set to the child control on a later event. Which event would it be? I am out of ideas.
Upvotes: 0
Views: 604
Reputation: 13456
So maybe the parent's font is set to the child control on a later event.
Yes, the font is changed when the child control is added to parent's Controls
collection.
Which event would it be?
You can handle child control's FontChanged
event to detect font changes specifically. You can also try ParentChanged
if you want to track when the parent's font is set.
How it actually works: Control.Font
has a getter that requests the parent's font if the font isn't explicitly set. This is covered in the documentation:
The Font property is an ambient property. An ambient property is a control property that, if not set, is retrieved from the parent control. ...
You can also check out the reference source for Control.Font
:
public virtual Font Font {
...
get {
Font font = (Font)Properties.GetObject(PropFont);
if (font != null) {
//return control's font if it was explicitly set.
return font;
}
Font f = GetParentFont();
if (f != null) {
//otherwise, try to retrieve and return parent control's font
return f;
}
....
return DefaultFont;
}
So, the font itself isn't set anywhere in the process. The return value of the property just changes automatically when the child control is assigned to the parent.
The same is true for other ambient properties: BackColor
, ForeColor
, RightToLeft
, etc. You can go through the implementation of Control.AssignParent
for reference.
Upvotes: 3