Looking for a Post-Constructor Event of a Control

2019-07-25 00:11发布

问题:

I have made a Label subclass and need to initialize a few of its Properties.

Some I can set in the constructor, but others are being reset in the designer code of the form, so they must be set

  • after the designer has done its InitializeComponent
  • but before the Paint event runs, which needs them in place.

Of course the control should be self-sufficient, so I can't add anything to the form's code.

I am using a workaround now: I set a flag bool needsInit = true; which I check in the Paint event. If true I call a doInit() method, which clears the flag and does the initializations.

It works, both for the running Form and for the VS Designer window.. but I smell a flag

So is there maybe a better, flagless way to do it? Or the Right Way?

回答1:

Override the InitLayout method.

protected override void InitLayout()
{
    // do something here
    base.InitLayout();
}