传递参数的构造函数里面的InitializeComponent创建的控件 [英] Passing constructor parameters to controls created inside InitializeComponent
问题描述
的InitializeComponent
设置组件的形式,但对于我已经创造了它调用默认的构造函数一个用户控件,但我想打电话给我自己的构造函数(带参数)在用户控件。样板code表示不修改的内容,那么什么是做到这一点的最好方法是什么?
您需要创建一个类型转换器类,并以 TypeConverterAttribute(typeof运算(MyTypeConverter))
。类型转换器会告诉Visual Studio中如何创建类型 - 让你控制什么被放在在InitializeComponent。
你可以去非常深,居然写C $ cDomSerializer定制$,您可以在其中,然后写出来的任何C#code你想要的 - 我用这个方法来强制InitializeComponent方法来解决从温莎城堡一切形式的控制!这个作品真的很好...
反正...
您会注意到MS已经使用这种技术类型是这样的:
this.treeView1 =新System.Windows.Forms.TreeView();
this.treeView1.Location =新System.Drawing.Point(72,104);
this.treeView1.Name =为TreeView1;
this.treeView1.Nodes.AddRange(
新System.Windows.Forms.TreeNode [] {
新System.Windows.Forms.TreeNode(NODE0),
新System.Windows.Forms.TreeNode(节点1)});
基本上 - 在你的类型转换器,你重写ConverterTo的方法,并返回一个新InstanceDescriptor,这将描述到的WinForms设计师,如何实例的类型(使用什么构造,以及什么样的参数传递)<。 / P>
您可以在这里找到堆的详细信息(包括基本实现): http://msdn.microsoft.com/en-us/library/ms973818.aspx
在InitializeComponent真的很强大,一旦你得到你的头周围所有的扩展点。 快乐编码!
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?
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!
这篇关于传递参数的构造函数里面的InitializeComponent创建的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!