在C#中扩展表单

Jef*_*y W 4 c# winforms

对于我的应用,我需要几种形式.这些表格都需要有一定的图片,需要有白色背景颜色.

而不是在VisualStudio中创建标准表单并编辑每个单独的具有这些规范的表单,有没有办法制作我自己的表单,我每次都可以使用?通过扩展它或许?

提前致谢.

TcK*_*cKs 5

与visual studio designer结合使用时要小心继承.如果你不是"朋友"与所有的设计师相关的属性(BrowsableAttribute,DefaultValueAttribute,...)和支撑构件(如MyProperty,ShouldSerializeMyProperty(),ResetMyProperty()),尝试重用代码和安全时可引起头痛.

如果可以,请使用合成而不是继承.我在设计师设计表单和为"内容"控件创建面板方面有很好的经验.

而内容控件可以继承自"usercontrol",您也可以在visual studio designer中设计它们.

之后,您可以将任何预先设计的表单与任何预先设计的控件组合在一起.

您描述的案例的简单示例:

/// <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();
Run Code Online (Sandbox Code Playgroud)


Jen*_*ter 4

是的。

制作一个基本表单 - 这是一个与其他表单一样的表单。

public class MyBaseForm : Form
Run Code Online (Sandbox Code Playgroud)

修改该表单,使其看起来像您想要的模板。

现在你所要做的就是让你的其余形式继承你刚刚创建的寺庙形式。

public class MyForm1 : MyBaseForm
Run Code Online (Sandbox Code Playgroud)

简单的 :-)