How to inherit a generic form and open it in the Visual Studio designer?
Asked Answered
Z

1

7

In my application, I have a BaseForm which has a generic member in it:

public partial class BaseForm<T> : Form where T : Presenter
{
    protected T Presenter;

    public BaseForm()
    {
        InitializeComponent();
    }
}

Now what i need is to have a form which is inherited from my BaseForm

public partial class SampleForm : BaseForm<SamplePresenter>
{
    public SampleForm()
    {
        InitializeComponent();
        Presenter = new SamplePresenter();
    }
}

The problem is that the Visual Studio designer does not show my SampleForm derived from BaseForm<T>.

It gives this warning:

Warning 1 The designer could not be shown for this file because none of the classes within it can be designed. The designer inspected the following classes in the file:

SampleForm --- The base class 'Invoice.BaseForm' could not be loaded. Ensure the assembly has been referenced and that all projects have been built. 0 0

How can I overcome this?

P.S. I looked at this post but didn't really get the whole idea of how to solve this.

Zoilazoilla answered 30/3, 2015 at 14:46 Comment(0)
B
10

The designer doesn't support this, as described in that post.

You need this base class:

public partial class SampleFormIntermediate : BaseForm<SamplePresenter>
{
    public SampleFormIntermediate()
    {
        InitializeComponent();
        Presenter = new SamplePresenter();
    }
}

And you need to use this class for the Visual Studio designer:

public partial class SampleForm : SampleFormIntermediate
{
}

In that way, Visual Studio 'understands' what to open in the designer and how to open it.

Binding answered 30/3, 2015 at 14:49 Comment(5)
Isn't the idea to have different presenters in different inheriting classes.Vanadous
@Magnus: OPs problem focusses on the Visual Studio designer integration. Nothing more. I think this is what it should be for that.Binding
Thanks, that's exactly what I was looking for. Now I can just have a test package where I'll be able to open the UI with the designer, and have the actual project implemented via generics. Thanks again:)Zoilazoilla
@Vanadous can you also provide a documentation or some other related links from which you have come up to the solution? The solution worked for me, now i'm wondering about actually why does the designer work that way.Zoilazoilla
This answer is very useful, especially considering that this workaround is definetely counterintuitive. Thanks.Cookery

© 2022 - 2024 — McMap. All rights reserved.