views:

250

answers:

1

Hello guys,

I have implemented a custom designer class which inherits from DocumentDesigner. The standard Form class in the .NET Framework uses the FormDocumentDesigner class (also inheriting from DocumentDesigner) but since this class is internal it is not possible to inherit from it and customize its behavior I copied the logic in this class by using a reflector and inserted it in my custom designer class (so that the default design time behavior for my form is compliant with the standard Form).

Everything works fine except one thing: in the Initialize method of my custom designer class I want to insert a ToolStrip control so that each time my form is opened while in design time, this control is visible and editable. The problem is that the Initialize method is called each time you close and reopen the form in the designer which causes each time new instance of the ToolStrip control to be created and added in the Controls collection of the form. I am looking for a way to check whether there is already a ToolStrip control serialized in the code and avoid adding another one.

Until now I found out that I can use the LoadComplete event of the IDesignerHost and check whether there is a ToolStrip in the Controls collection of the Form. However, any better ideas would be appreciated.

Thanks for your time! :-)

A: 

Well, the LoadComplete event is the correct point. I usually check the Loading property to check if the Initialize is happening while loading or it has been called after the load.

IDesignerHost _host;
Form _form;

public override void Initialize(System.ComponentModel.IComponent component)
{
  _form = component as Form;
  _host = (IDesignerHost)this.GetService(typeof(IDesignerHost));
  if (_host != null)
  {      
   if (_host.Loading)
   {
     _host.LoadComplete += new EventHandler(_host_LoadComplete);
   }
   else
   {
     initializeForm();
   }
  }
}

void _host_LoadComplete(object sender, EventArgs e)
{
  _host.LoadComplete -= new EventHandler(_host_LoadComplete);
  initializeForm();
}

void initializeForm()
{
   if (_form!= null)
   {
      ...
   }
}

Another approach is to create a Component that you can drop into a form and create a designer for the component instead of recreating the FormDesigner. From the component designer you can get the parent form using the _host.RootComponent property.

jmservera