Domanda

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?

È stato utile?

Soluzione

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!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top