繁体   English   中英

有没有办法在TabControl中禁用TabPage?

[英]Is there a way to disable a TabPage inside a TabControl?

我真的不需要禁用它们,因为我要么禁用TabControl要么启用它。 但是当TabControl被禁用时,我希望标签页看起来被禁用(灰色)。

人们在下面提到的不会单独做到这一点,但他们会结合起来。 试试这个:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        //Disable tabPage2
        this.tabPage2.Enabled = false; // no casting required.
        this.tabControl1.Selecting += new TabControlCancelEventHandler(tabControl1_Selecting);
        this.tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed;
        this.tabControl1.DrawItem += new DrawItemEventHandler(DisableTab_DrawItem);
    }
    private void DisableTab_DrawItem(object sender, DrawItemEventArgs e)
    {
        TabControl tabControl = sender as TabControl;
        TabPage page = tabControl.TabPages[e.Index];
        if (!page.Enabled)
        {
            //Draws disabled tab
            using (SolidBrush brush = new SolidBrush(SystemColors.GrayText))
            {
                e.Graphics.DrawString(page.Text, page.Font, brush, e.Bounds.X + 3, e.Bounds.Y + 3);
            }
        }
        else
        {
            // Draws normal tab
            using (SolidBrush brush = new SolidBrush(page.ForeColor))
            {
                e.Graphics.DrawString(page.Text, page.Font, brush, e.Bounds.X + 3, e.Bounds.Y + 3);
            }
        }
    }

    private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
    {
        //Cancels click on disabled tab.
        if (!e.TabPage.Enabled)
            e.Cancel = true;
    }
}

尝试使用此代码它的工作原理:

private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if (e.TabPage == tabControl1.TabPages[1])
            {
                e.Cancel = true;
            }            
        }

在if条件中保留要禁用的标签页的索引或名称,我将索引保持为1. :)

重写了@Corylulu提供的解决方案,以封装控件本身的所有内容。

public class DimmableTabControl : TabControl
{
    public DimmableTabControl()
    {
        DrawMode = TabDrawMode.OwnerDrawFixed;
        DrawItem += DimmableTabControl_DrawItem;
        Selecting += DimmableTabControl_Selecting;
    }

    private void DimmableTabControl_DrawItem(object sender, DrawItemEventArgs e)
    {
        TabPage page = TabPages[e.Index];
        using(SolidBrush brush = new SolidBrush(page.Enabled ? page.ForeColor : SystemColors.GrayText))
        {
            e.Graphics.DrawString(page.Text, page.Font, brush, e.Bounds.X + 3, e.Bounds.Y + 3);
        }
    }

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

暂无
暂无

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

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