TabControl - Disable/Enable tab page

You can't disable a tab as such, but you could mimic it.

You could do something like the following:

1. Add a TabControl with 2 pages
2. Set DrawMode to OwnerDrawFixed
3. Attach the TabControl.Selecting event to tabControl1_Selecting
4. Attach the TabControl.DrawItem event to tabControl1_DrawItem
5. Then copy the following code into your form (you will have to change it a little)

   

 

  public Form1()
  {
   InitializeComponent();

   tabPage2.Enabled = false;

  }
  private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
  {
   if (!e.TabPage.Enabled)
   {
    e.Cancel = true;
   }
  }

  private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
  {
   TabPage page = tabControl1.TabPages[e.Index];

   if (!page.Enabled)
   {
    using (SolidBrush brush = new SolidBrush(SystemColors.GrayText))
    {
     e.Graphics.DrawString(page.Text, page.Font, brush, e.Bounds);
    }
   }
   else
   {
    using (SolidBrush brush = new SolidBrush(page.ForeColor))
    {
     e.Graphics.DrawString(page.Text, page.Font, brush, e.Bounds);
    }
   }
  }


 


Basically what you are doing is drawing your own tabs. You are disabling the TabPage in your constructor - be aware that the TabPage.Enabled is not visible in the designer or intellisense - but it does exist.

Then in the selecting event you are stopping the focus from changing to a disabled page. In the DrawItem you are drawing the tabs yourself, so that you can mimic the disabled tab.

This is not a complete solution, but it will get you started.

HTH

David
posted @ 2011-11-14 13:43  晓炜  阅读(644)  评论(0)    收藏  举报