Question

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.

Was it helpful?

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.

OTHER TIPS

Sometimes the easiest thing to do in this case is to make an empty subclass that qualifies the generic parameter.

This is often done with the ObservableCollection:

public class SomeItemCollection : ObservableCollection<SomeItem>{

}

It is kind of irritating, but it may solve your problems.

Like the others have stated, the Visual Studio Designer has a lot of trouble handling generics in controls. I've run into this myself when trying to implement something like a generic 'property viewer' class.

The solution that worked for me was defining an intermediary class, like Egor said. If I understand your question correctly, for your situation, that should be something like this:

public class PictureElementGallery : Gallery<PictureElement>

Then use the PictureElementGallery on your form, instead of Gallery < PictureElement >. The designer should have no trouble with that.

Instead of having a generic control, have the control interact with a generic class that is separate from the control itself. Then pass this class into the control.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top