开发者

Creating a custom TabPage control in C#

开发者 https://www.devze.com 2022-12-23 20:12 出处:网络
I\'m building a small tabbed c# Form and I\'d like each tab page to have some common features, notably, an OK button and an error message and to h开发者_StackOverflowave a space for the specific form

I'm building a small tabbed c# Form and I'd like each tab page to have some common features, notably, an OK button and an error message and to h开发者_StackOverflowave a space for the specific form fields.

Has anyone else done something similar and how did you approach it?


This is easy to do without extending either TabControl/TabPage.

Define one UserControl, and put the common elements on it you want on every TabPage.

On the Form: go ahead and design the TabPage specific controls you want for each TabPage : make sure they are not going to visually overlap with the common controls once the UserControl has been added.

In the Form Load Event of your main Form do something like this :

    // form scoped variable to hold a referece to the current UserControl
    private UserControl1 currentUserControl;

    private void Form1_Load(object sender, EventArgs e)
    {
        foreach(TabPage theTabPage in tabControl1.TabPages)
        {
            currentUserControl = new UserControl1();

            theTabPage.Margin = new Padding(0);
            theTabPage.Padding = new Padding(0);

            theTabPage.Controls.Add(currentUserControl);

            currentUserControl.Location = new Point(0,0);

            currentUserControl.Dock = DockStyle.Fill;

            currentUserControl.SendToBack();
        }
    }

Even though the 'SendToBack isn't really required here it is "insurance" that your UserControl with the 'Okay button and TextBox for an error message are placed behind the individual controls you have assigned to each TabPage.


Several ideas:

  • Keep the common controls outside the tabpanel;
  • Extend the TabPage/TabControl
  • Create a base UserControl with the common buttons and make usercontrols that inherit from it. Then place one inherited usercontrol per TabPage.
0

精彩评论

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