c# - Constrain a control's Parent to a particular type in Windows Forms with .NET -
i want write control can have parent of type form
(or derivatives).
i guess might liken behaviour tabcontrol
, or tabpage
, tabcontrol
cannot have children not of type tabpage
, , tabpage
cannot have parent not tabcontrol
.
however implementation differs because unlike tabcontrol
, want form
accept type of control, control should ever have parent of type form
.
here have tried:
public class customcontrol : containercontrol { protected override void onparentchanged(eventargs e) { base.onparentchanged(e); if (!(this.parent form)) { this.parent.controls.remove(this); throw new argumentexception("customcontrol can child of form"); } } }
this causes undesired effects in forms designer, such as:
- throws exception when trying load form in designer.
- throws exception when removing control form.
- the control not resize properly.
i'd appreciate recommendation on how fix this, or points going wrong.
as quite said, simplest answers best...adding additional check if
statement fixes everything! - silly me! should have tried sooner!
public class customcontrol : containercontrol { protected override void onparentchanged(eventargs e) { base.onparentchanged(e); if (this.parent != null && !(this.parent form)) { this.parent.controls.remove(this); throw new argumentexception("customcontrol can child of form"); } } }
Comments
Post a Comment