[ACCEPTED]-C# generics usercontrol-user-controls

Accepted answer
Score: 37

This works

public class Control1<T> : UserControl { ... }

public class Control2 : Control1<double> { ... }

public class Control3 : Control2 { ... }

had read it here:

Generic User Controls?


Score: 12

Sounds much like what we do in our project.

There's 5 a base class that is generic:

public partial class controlItemList<TBaseItem, TBaseItemCollection> : UserControl, IUIDispatcher
    where TBaseItem : new()
    where TBaseItemCollection : IItemCollection<TBaseItem>

Then for each 4 use we define a non-generic version (which 3 still couldn't be used by designer):

public class controlMessagesNonGenericParent : controlItemList<MailItem, MailItemCollection>

... and 2 then we have derived controls that could 1 be used in designer:

public partial class controlMessages : controlMessagesNonGenericParent
Score: 3

There are some restrictions on what your 15 control can or cannot do in order to be 14 able to use the designer. Fundamentally 13 they all revolve around the designer being 12 able to instantiate your class (must have 11 a parameterless constructor, can't be abstract, etc.). Because 10 the designer has no idea what type to pass 9 as a generic argument (and I doubt this 8 is even a consideration), your class can't 7 be instantiated.

Your best hope would be 6 to create your UserControl and change the constructor 5 to protected (this, I believe, will work, since the 4 designer uses reflection and ignores visibility, but 3 I'm not 100% positive). You can then inherit 2 from that UserControl and create your generic class 1 and call the base (protected) constructor.

Score: 2

I don't know at which point (with which 9 C#/.NET/VS verison update), but now it is 8 possible to create generic control the same 7 way you create any other generic class.

If 6 you create your UserControl in VS the standard way 5 (i.e. by adding it through GUI), you simply 4 add <T> in both parts of class declaration 3 ("base" class code and the designer managed 2 file). Actually, that is what you have in 1 your quoted code.

Score: 0

I don't believe this is possible, because 3 the designer invokes an instance of your 2 class. If you use generics, the designer 1 doesn't know what type to pass into 'T'.

Score: 0


The bug has been posted to microsoft's site 2 and you can see that its marked as "Postponed" currently 1 there is no solution !! .

More Related questions