views:

44

answers:

4

I have my own control derived from Windows.Forms.Control and I am checking the Parent.BackColor inside the overrided of OnHandleCreated() method. At desing-time the Parent property first returns null, then - after form is completely loaded - returns the real parent window: the form itself.

We need to draw part of the custom control with the same color of the parent form background: when can we rely on the Control.Parent value?

Thanks.

A: 

you can use if( this.DesignMode ) return; to determine if your control is in design and not get exception or to do additional checking. In Windows Forms, after InitilizeComponents, afaik Control always have parent.

Andrija
After `InitializeComponent` in the parent, that's correct. *Not* after `InitializeComponent` in the control.
Adam Robinson
yeah, that's what I meant, thanks :)
Andrija
A: 

Here's a citation from Chris Sells' book Windows Forms Programming in C# (p. 259):

An ambient property is one that, if it's not set in the control, will be "inherited" from the container. Of all the standard properties provided by the Control base class, only four are ambient: BackColor, ForeColor, Font, and Cursor. [...]    (Emphasis added by me.)

Maybe this can somehow help avoiding the dependency on the Control.Parent property...?


P.S.: Actually, some of the other answers are probably more useful than mine: I start thinking that perhaps, the OnHandleCreated method is simply the wrong place to ask for a property of the control's parent. OnParentChanged or even OnPaint are probably better places for that.

stakx
+2  A: 

You can use the ParentChanged event to detect when that property changes and trigger a redraw (though one should occur automatically). There are some properties, however (BackColor and ForeColor being two of them, I believe) that are "inherited" from the parent if not set explicitly, so you should be able to use those as well.

Adam Robinson
A: 

Actually I do not see problem here. Because as I understand you need parent for drawing something with parent back color, and when you receive your control's Paint event (OnPaint, WM_PAINT) parent already initialized.

arbiter