Continue to my previous question (link)
What if I want to assign the font of a new user control to its creator's font. Should I do this a):
newControl = new MyControl(...);
...
newControl.Font = this.Font;
or this b)?
newControl = new MyControl(...);
...
newControl.Font = (Font)this.Font.Clone();
If answer is a), what will happen to the new user control's font if the creator's font get disposed (for example, a window closed by user)?
Thanks,
Gilbert
If you are trying to enforce a constant look / feel about your application... such as all labels using Font X, Size Y, Color Z across ALL your forms, I would define my own class from a label, and declare these elements with read-only GETTER calls and no SETTER. This will PREVENT the designer from even serializing such information. So, you change the font info ONCE at your root class, and all the locations your label is used will be force to the font. You may have to tweak alignments based on changes, but all the visual aspects will remain. Additionally, I've done this with textbox, combobox, multi-line textbox, buttons, checkboxes too. Works great. So, when I started the given elements as read-only, the build of the app would kick out a bunch of errors about read-only properties. So, I would quickly scan through and delete the designer's serialized elements and cleaned it up. Works like a charm. If this is what you are looking to do, I can offer more sample code on how I've implemented it.
The Font
class actually encapsulates two things:
The text style encapsulated by a Font
class is immutable; the handle is "disposable immutable", meaning that it will never encapsulate any GDI handle other than the one with which it was created, but once the Font
is disposed it will cease to encapsulate any font handle (it becomes truly immutable, albeit useless, at that point).
Setting the Font
property of the controls in the Framework will cause it to grab two things:
The identity of the Font
object used to set the property, which is used solely by the Font
property getter
The text style, which the control will use to create its own private Font
object.
Because each Framework control will inherently clone any Font
instance used to set its Font
property, there's generally no need for user code to clone a font before using it to set another control's Font
property.