Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending a Form in C#

Tags:

c#

winforms

For my application I need several forms. These forms all need to have a certain picture and need to have a white background color.

Instead of creating a standard Form in VisualStudio and editing each one of the individualy to have these specifications, is there a way to make my own Form that I can use each time? By extending it perhaps?

Thanks in advance.

like image 430
Jeffrey W Avatar asked Nov 25 '15 19:11

Jeffrey W


2 Answers

Be careful with inheritance in combination with visual studio designer. If you are not "friend" with all the designer-related attributes (BrowsableAttribute, DefaultValueAttribute, ...) and support members (such as MyProperty, ShouldSerializeMyProperty(), ResetMyProperty()), the attempt to reuse code and safe time can cause headache.

If you can, use composition instead of inheritance. I have good experience with designing the form in designer and create panels for "content" controls.

And the content controls can inherit from "usercontrol", co you can design them in visual studio designer too.

After that, you can just combine any predesigned form with any predesigned control.

The simple example of case you described:

/// <summary>
/// Form with "skeleton" common for your application.
/// </summary>
public partial class FormWithPicture : Form {
    private Control content;
    /// <summary>
    /// The control which should be used as "main" content of this form.
    /// </summary>
    public Control Content {
        get { return this.content; }
        set {
            this.content = value;
            // the "panel1" is the container of the content
            this.panel1.Controls.Clear();
            if (null != value) {
                this.panel1.Controls.Add(value);
            }
        }
    }

    public FormWithPicture() {
        InitializeComponent();
    }
}

// somewhere else
new FormWithPicture {
    Content = new ContentControl_A()
}.Show();
like image 111
TcKs Avatar answered Oct 30 '22 09:10

TcKs


Yes.

Make a base form - that is a form like any other.

public class MyBaseForm : Form

Modify that form so that it looks like the templets you want.

Now all you have to do, is to make the rest of your forms inherit the templeform you just created.

public class MyForm1 : MyBaseForm

Easy :-)

like image 28
Jens Kloster Avatar answered Oct 30 '22 10:10

Jens Kloster