简体   繁体   中英

Visual Studio changes designer generated code when I create a new class inheriting from Form

As per recommendation I ask this question in a new thread. The question stems off an answer by Reza given to this question , where I wanted custom properties to show up in the form's designer.

To accomplish this, I need to create a class, let's call it BaseForm and let BaseForm inherit from System.Windows.Forms.Form and I should add my desired properties to this class and let my user form inherit from BaseForm . Like this:

public partial class BaseForm : Form
{
    [Browsable(true), Description("test property"), Category("Appearance")]
    public Color bCol { get; set; }
}

public partial class Form1 : BaseForm
{
    public Form1()
    {
        InitializeComponent();
    }
}

When I do this, however, Visual Studio changes the designer generated partial class Form1 , where the InitializeComponent etc. is located, to partial class BaseForm . This comes with the error that InitializeComponent is not in the scope of Form1 so I change it to this:

public partial class BaseForm : Form
{
    [Browsable(true), Description("test property"), Category("Appearance")]
    public Color bCol { get; set; }
    public BaseForm()
    {
        InitializeComponent();
    }
}

public partial class Form1 : BaseForm
{
    /*public Form1()
    {
        InitializeComponent();
    }*/
}

This is defeating the purpose of having Form1 inheriting from BaseForm because what I see in the designer is BaseForm which inherits from Form , instead of Form1 which inherits from BaseForm as I wish to do.

Why is Visual Studio doing this and what could I do to fix this?

The designer edits the first class in your file. You have put BaseForm as first class in your .cs file.

To solve the problem, make it in a separate file or move the codes for BaseForm after Form1 codes.

In general it's better to keep code of BaseForm separate, so it's better to add new form to the project and name it BaseForm and add additional properties to the form, then for other forms, add Inherited Form or add new Form and change the base class name manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM