我真的不需要禁用它们,因为我要么禁用TabControl
要么启用它。但是当禁用TabControl
时,我希望标签页看起来已禁用(灰色)。
答案 0 :(得分:6)
下面提到的人不会单独提出这个伎俩,但他们会合并。试试这个:
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;
}
}
答案 1 :(得分:3)
尝试使用此代码:
private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
{
if (e.TabPage == tabControl1.TabPages[1])
{
e.Cancel = true;
}
}
在if条件中保留要禁用的标签页的索引或名称,我将索引保持为1。 :)
答案 2 :(得分:2)
重写了@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;
}
}
}