开发者

How to get InitializeComponent to instantiate a derived control at runtime in a C# control

开发者 https://www.devze.com 2023-01-08 19:13 出处:网络
I have developed a generic TreeList control in C# which combines a TreeView with a ListView to obtain a multi-column TreeView.

I have developed a generic TreeList control in C# which combines a TreeView with a ListView to obtain a multi-column TreeView.

I would like to use a TreeView derived class for the TreeView portion of the control, but keep the TreeListView control generic.

In my TreeListView I have a member variable:

protected TreeView treeView;

and the Initializ开发者_Go百科eComponent function creates the treeView:

private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.listView = new System.Windows.Forms.ListView(); this.treeView = new System.Windows.Forms.TreeView();

So if I have a derived TreeView class called MyTreeView, is there any way in which I could get InitializeComponent to do something like:

this.treeView = new MyTreeView() but somehow specifying the type of class to instantiate at runtime, e.g. this.treeView = new (typeof(type specified in constructor)?


No, the InitializeComponent is an automatically-generated method and any changes you make will be reverted when you modify with the designer (well, who knows when). You can't control the code generation in the way that you want.

You should leave InitializeComponent as-is, and create the object for treeView afterwards, in your constructor, programatically.

Hope that helps.


this.treeView = new (typeof(type specified in constructor)

To create an instance of a class at runtime, use:

MyObject obj = Activator.CreateInstance(myType);


Use the designer to drag and drop a standard control (I often use a Panel for this). In the properties of the control, set the name to something you recognise.

Next, open the Form.Designer.cs file (assuming you're in VS2005 or above) and search through the text for the definition of the control instance. Change the type from Panel to your control type, then search for the instantiation of the control and change from New Panel() to new Treeview().

After saving, compile the code and open the designer -- your panel will change into your tree control and you can continue as normal. This change will persist if you come back and change the form through the designer. I do this a lot in my current projects because we have slightly different control versions for different customers so as can't add them all to the toolbox.


The issue is that I want to keep a generic version of my TreeList control but I also want a specialised version that will use a derived TreeView control within it.

I want to be able to do this without having to modify the generic version of the TreeList control.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号