5

InitializeComponent sets up the components on the form, however for a Usercontrol that I have created it calls the default constructor but I want to call my own constructor (with parameters) on the usercontrol. The boilerplate code says don't edit the contents, so what is the best way to do this?

Adi Lester
  • 24,731
  • 12
  • 95
  • 110
John Fleming
  • 267
  • 1
  • 3
  • 12
  • You can't do that. What would the designer do? – SLaks Sep 23 '12 at 22:13
  • Possible duplicate of http://stackoverflow.com/q/1784303/389966 – Adi Lester Sep 23 '12 at 22:14
  • @SLaks yes that is why I am asking, I tried it and it caused a problem, not so much with the designer but more with usercontrol being reinitialized and the code not acting as expected. I thought MS would have considered this at some point. – John Fleming Sep 24 '12 at 00:27

1 Answers1

5

You need to create a TypeConverter class, and decorate your UserControl with a TypeConverterAttribute(typeof(MyTypeConverter)). The type converter will tell Visual Studio how to create your types - allowing you to control what gets put in the InitializeComponent. You can go REALLY deep, and actually write a custom CodeDomSerializer, in which you can then write out ANY C# code you want - I used this technique to force the InitializeComponent method to resolve all Forms controls from Castle Windsor! That works really well...

Anyway...

You'll notice MS already uses this technique for types like this:

this.treeView1 = new System.Windows.Forms.TreeView();
this.treeView1.Location = new System.Drawing.Point(72, 104);
this.treeView1.Name = "treeView1";
this.treeView1.Nodes.AddRange(
new System.Windows.Forms.TreeNode[] {
  new System.Windows.Forms.TreeNode("Node0"),
  new System.Windows.Forms.TreeNode("Node1")});

Basically - in your TypeConverter, you override the 'ConverterTo' method, and return a new InstanceDescriptor, which will describe to the WinForms designer, HOW to instantiate your type (what constructor to use, and what arguments to pass).

You can find heaps more information here (including basic implementation): http://msdn.microsoft.com/en-us/library/ms973818.aspx

InitializeComponent is REALLY powerful, once you get your head around all the extensibility points. Happy coding!

Adam
  • 4,159
  • 4
  • 32
  • 53