Thursday, March 14, 2013

How to design Windows Forms with Abstract Inheritance?

It happened few days ago when I got to this nice error:

The designer must create an instance of type '... .BaseClass.TabBaseControl' but it cannot because the type is declared as abstract.


The scenario was like this: I had a Base class where a defined abstract members that where implemented in a form. When wanted to see the design of the page this warning appeared even though the application runs just fine. So how to get rid of this error:  "The designer must create an instance of type 'SchedeMaterialiDaTaglio.BaseClass.TabBaseControl' but it cannot because the type is declared as abstract. " ?
Well, searching around I got to this post http://www.platinumbay.com/blogs/dotneticated/archive/2008/01/05/designing-windows-forms-with-abstract-inheritance.aspx where I found part of the solution. 
Here it is:

 public class AbstractCommunicatorProvider : TypeDescriptionProvider
    {
        public AbstractCommunicatorProvider()
            : base(TypeDescriptor.GetProvider(typeof(UserControl)))
        {
        }
        public override Type GetReflectionType(Type objectType, object instance)
        {
            return typeof(UserControl);
        }
        public override object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args)
        {
            objectType = typeof(UserControl);
            return base.CreateInstance(provider, objectType, argTypes, args);
        }
    }
You define this class in inherited class(it only worked for me in this way) and you must also put this for base class and inherited class:

    [TypeDescriptionProvider(typeof(AbstractCommunicatorProvider))]
    public partial class TabUC : TabBaseControl{}

    [TypeDescriptionProvider(typeof(AbstractCommunicatorProvider))]
    public abstract class TabBaseControl : UserControl, ITabBase{}
Of course that you will have to include System.ComponentModel namespace and others just as needed.
Hope it helped. Ciao.

No comments:

Post a Comment