自定义通用用户控件未出现在工具箱中

Fed*_*are 2 c# generics user-controls windows-forms-designer winforms

我需要使用泛型创建自定义用户控件,因为我有一个BindingSource类型为数据源的用户控件T

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

在表单设计器中,自定义用户控件不会出现在工具箱中,因为它是通用的。解决办法是什么?

Rez*_*aei 5

这是工具箱的预期行为。

将控件从工具箱拖放到窗体上时,您是在命令设计器创建该控件的实例。您不能在GenericControl<T>没有确定的情况下创建 的实例T。相反,您需要一个GenericControl<SomeClass>.

所以通用控件没有出现在工具箱中是完全有道理的,因为它在设计器中没有使用,并且设计器在创建实例时不知道它应该为通用参数使用什么类型。

同样关于设计器,考虑这篇文章:从VS2015.1开始的 UserControl 通用基类,Windows 窗体设计器显示了具有通用基类的类,没有任何问题。以下类将毫无问题地显示在设计器中:

public class SomeClassControl:GenericControl<SomeClass>
{
}
Run Code Online (Sandbox Code Playgroud)

对于旧版本的 Visual Studio,请使用链接帖子中描述的解决方法:

public class SomeClassControl:SomeClassControlBase
{
}
public class SomeClassControlBase:GenericControl<SomeClass>{}
Run Code Online (Sandbox Code Playgroud)