Search code examples
c#genericsuser-controlstypesdesignmode

C# typed <T> usercontrol in design mode gives error


I've got a custom class, which derives from UserControl. The code:

public partial class Gallery<T> : UserControl where T : class, IElement, new()

This classworks like it's supposed to work. But, when I try to enter design mode of the form which contains these Gallery classes, it gives me errors:

  • Could not find type 'PresentrBuilder.Forms.Gallery'. Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built.

  • The variable 'pictureGallery' is either undeclared or was never assigned.

Note: (pictureGallery actually is a Gallery<PictureElement>).

How can solve this? This way, I can't work in design mode which makes creating my userinterface quite hard.


Solution

  • The designer hates (i.e. doesn't support) generic controls, and that isn't going to change any time soon, so don't do that. Instead, consider having a property (or similar) that accepts a Type, and do some work at runtime (reflection etc) - or: don't use the designer.

    For example, if you have:

    public Type ControlType {get;set;} // comparable to T in the original
    

    You can use:

    IElement el = (IElement) Activator.CreateInstance(ControlType);
    

    This will give you everything you currently have (new, IElement, etc) - but it just can't do any validation at compile-time.