简体   繁体   中英

Custom Generic UserControl doesn't appear in Toolbox

I need to create a custom User Control with generics because I have a BindingSource with a data source of type T

public partial class ABMControl<T> : UserControl
{
    public ABMControl()
    {
        InitializeComponent();
        this.bindingSource.Datasource = typeof(T);
    }
}

In the form designer the custom user control does not appear in toolbox because is generic. What is the solution?

It's expected behavior for toolbox.

When dropping a control from toolbox onto your form, you are commanding the designer to create an instance of that control. You cannot create an instance of GenericControl<T> without determining T . Instead you need an instance of GenericControl<SomeClass> .

So it completely makes sense the generic control doesn't appear in toolbox because it has no usage in designer and designer doesn't know what type should it use for generic parameter when creating instance.

Also about designer, considering this post: Generic Base Class for UserControl starting from VS2015.1 , Windows Forms Designer shows classes which have generic base classes without any problem. The following class will be shown in designer without any problem:

public class SomeClassControl:GenericControl<SomeClass>
{
}

For older versions of Visual Studio, use the workaround which is described in the linked post:

public class SomeClassControl:SomeClassControlBase
{
}
public class SomeClassControlBase:GenericControl<SomeClass>{}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM