C#.NET:TabControl的TabPage禁用/启用实现

时间:2016-05-10 20:42:10

标签: c# .net tabcontrol system.drawing tabpage

我找到了tabPages的Enabled属性的一些实现,因为它在UI中的实现是隐藏的,但我不知道如何使用它。它可能会成为一个愚蠢的问题,但我真的只是从c#和.net平台开始。我想从第一个表单中获取一个变量,这是一个登录表单,如果选中一个复选框则发送一个真值;如果不是,则返回false,如果是,则登录为具有权限的管理员访问所有选项卡,但如果为false,则用户将被限制访问某些选项卡。我不知道如何限制对这些标签的访问,或允许它。代码如下:

表单构造函数的代码:

public Form1()
{
InitializeComponent();

this.tabControl1.DrawMode = 
TabDrawMode.OwnerDrawFixed;
this.tabControl1.DrawItem += 
new DrawItemEventHandler(DisableTab_DrawItem);
this.tabControl1.Selecting += 
new TabControlCancelEventHandler(DisableTab_Selecting);
}

绘制标签页的功能:

/// <summary>
/// Draw a tab page based on whether it is disabled or enabled.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PageTab_DrawItem(object sender, DrawItemEventArgs e)
{
TabControl tabControl = sender as TabControl;
TabPage tabPage = tabControl.TabPages[e.Index];

if (tabPage.Enabled == false)
{
using (SolidBrush brush = 
new SolidBrush(SystemColors.GrayText))
{
e.Graphics.DrawString(tabPage.Text, tabPage.Font, brush, 
e.Bounds.X + 3, e.Bounds.Y + 3);
}
}
else
{
using (SolidBrush brush = new SolidBrush(tabPage.ForeColor))
{
e.Graphics.DrawString(tabPage.Text, tabPage.Font, brush, 
e.Bounds.X + 3, e.Bounds.Y + 3);
}
}
}

阻止在禁用选项卡时选择选项卡的事件处理程序:

/// <summary>
/// Cancel the selecting event if the TabPage is disabled.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PageTab_Selecting(object sender, TabControlCancelEventArgs e)
{
if (e.TabPage.Enabled == false)
{
e.Cancel = true;
}
}

上述变量和决定声明:

 int cont = Login.accountType; //the variable from the first tab, that decides whether the account is admin type or client type
        //the variable is public static int in the first form

        if (cont == 1)
        {
            //display all the tabs, because we logged in as admin
        }
        else if(cont == 0)
        {
            //disable the tabs that we do not want the client to access
        }

1 个答案:

答案 0 :(得分:0)

我已经学会了如何使用它,它没有出现在intellisense中,这一开始让我很困惑,但确实有效。

    int cont = Login.accountType; //the variable from the first tab, that decides whether the account is admin type or client type
    //the variable is public static int in the first form

    if (cont == 1)
    {
        tabControl1.TabPages[0].Enabled = true;
        tabControl1.TabPages[1].Enabled = true;
        tabControl1.TabPages[2].Enabled = true;
        tabControl1.TabPages[3].Enabled = true;
    }
    else if(cont == 0)
    {
        tabControl1.TabPages[1].Enabled = false;
    }

这将启用管理员的所有选项卡,它将为客户端禁用一个选项卡,其中包含管理员将新帐户插入ms-access数据库的文本框。