繁体   English   中英

在 Windows Forms (.Net 4) 应用程序中,如何为所有 forms 定义基本表单样式?

[英]In a Windows Forms (.Net 4) application, how can I define a base form style for all forms?

例如,我希望我的所有 forms 都具有相同的IconStartPosition 但是,我还需要能够以通常的方式定义每种表单中的内容,拖放控件等。

这可能吗?

创建一个表单并按照您想要的方式设置 Icon 和 StartPosition 属性。 编译。 这将是您的基本形式。 现在使用 Project + Add New Item,Windows Forms 节点并选择 Inherited Form 项目模板。 IDE 将提示您输入基本形式 select。

go 的另一种方法是设置所有参数的扩展方法:

public static class FormExtentsions
{
    public static void SetDefault(this Form form)
    {
        form.Icon = new Icon("path");
        form.StartPosition = FormStartPosition.CenterScreen;
    }
}

像这样使用它:

public partial class Form1 : Form
{
    public Form1()
    {
        // Put it here if you want to be able to override everything
        this.SetDefault();

        InitializeComponent();

        // Put it here if you want the defualt to override "local" settings
        this.SetDefault();

    }
}

只需创建您自己的基本Form class:

class FormBase : Form
{
    public FormBase()
    {
        Icon = SomeIcon;
        StartPosition = StartPosition.Whatever;
    }
}

You could have a static Icon and Position, initialize it with a static constructor, and then make a constructor where you initialize the instance's Icon and Position properties with the static Icon and position: Fx.

class Foo : Form {
  static Bitmap sIcon     { get; private set; }
  static Point  sPosition { get; private set; }

  static Foo() {
    sIcon     = /* Load from external source */
    sPosition = new Point( x, y ); //Insert x and y
  }

  public Foo()
  : base() {
    Icon     = Foo.sIcon;
    Position = Foo.sPosition;
  } 
}

然后在创建 forms 时使用“Foo”作为基本形式。

我没有检查“图标”和“位置”的引用,所以我不知道它们是否存在,但你明白了:)

是的,但请记住,forms inheritance 在设计师支持方面有些不稳定。 请记住,任何需要子 forms 访问的控件必须将其修饰符更改为ProtectedInternal将适用于同一程序集中的 forms,但也会将控件公开给任何 class; Public应该是同一程序集避免)。 这包括面板或其他容器之类的东西,如果您的基本表单必须定义一些基本的表示元素,您可能会想要使用它们,因此您需要将子表单包含到特定区域。

为此,只需像创建任何其他表单一样创建基本表单,然后在 go 创建新的 forms 时,选择“继承的表单”而不是“表单”,然后选择 Z99938282F04071859941E18F16EFCF4。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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