开发者

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

For example, I'd like all of my forms to have the same Icon and StartPosition. Howe开发者_JS百科ver I also need to be able to define things in each form how you normally would, dragging and dropping controls, etc.

Is this possible?


Create a form and set the Icon and StartPosition properties the way you want them. Compile. This will be your base form. Now use Project + Add New Item, Windows Forms node and pick the Inherited Form item template. The IDE will prompt you to select the base form.


Antoher way to go, is to make an extension method where you set all the parameters:

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

The use it like this:

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();

    }
}


Simply create your own base 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;
  } 
}

Then use "Foo" as your base form when creating your forms.

I didn't check references for the "Icon" and "position" so I don't know if they exists, but you get the idea :)


Yes, but bear in mind that forms inheritance is somewhat flaky in terms of designer support. Just keep in mind that any controls that need to be accessible to child forms must have their modifier changed to Protected (Internal will work for forms in the same assembly, but will also expose the control to ANY class in the same assembly; Public should be avoided). This includes things like panels or other containers, which you'll likely want to use if your base form has to define some basic presentation elements, so you'll want to contain the child form to a particular area.

To this, just create your base form as you would any other form, then when you go to create new forms, choose "Inherited Form" instead of "Form", and select your base form.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜