tags:

views:

114

answers:

1

I made a custom control that is basically a multiline TextBox that allows input, and some other controls on the side that report some information. Now, I wanted to allow the user of my control to change the font in the TextBox, and thought something along the lines of: "Well, the user shouldn't be able to change the font of other controls, so I'll link it through the Font property on the control", and hence ended up with the following code:

public override Font Font {
    get { return txtEntry.Font; }
    set { txtEntry.Font = value; }
}

(Yes, hungarian notation on my controls... Old VB habits die hard...)

Now, this would appear fine, except that when I built my project and went back to my form to see the effect, Visual Studio crashed. And crashed reliably when starting the project back up again... I opened the class in Notepad and changed it to a different name, deleted the output folders and opened Visual Studio, rebuilt, and it's all working fine now.

My question is this: is there some inherant design flaw in my idea, or is this purely a VS bug?

+8  A: 

Font is an ambient property. This means that, if it is not set, the control looks at the parent's property to get its value. So, you have a recursive function because the parent's Font property looks at the child's, and around we go.

Windows forms controls use ambient properties, so child controls can appear like their surrounding environment. In this context, "ambient" means that the property is, by default, retrieved from the parent control. If the control does not have a parent and the property is not set, the control tries to determine the value of the ambient property through the Site property.

If the control is not sited, if the site does not support ambient properties, or if the property is not set on the AmbientProperties object, the control uses its own default values. Typically, an ambient property represents a characteristic of a control, such as BackColor, that is communicated to a child control. For example, by default a button will have the same BackColor as its parent form.

BTW, don't feel bad; I asked the exact same question once :-)

Ed Swangren
ie. Visual Studio was crashing from a stack overflow... Makes sense I suppose.
Matthew Scharley
Yeah, it will do that. I hit that sometimes when I return the Property itself in a 'getter', making it recursive. Open up the designer and BLAM!, crash.
Ed Swangren
Though I would say that it would be nice if the IDE did not crash because of it. Reminds of the vb6 debugger and how it would often crash if your program did. Useful.
Ed Swangren