65.9K
CodeProject 正在变化。 阅读更多。
Home

具有禁用项的列表框

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.81/5 (11投票s)

2009年4月2日

CPOL

2分钟阅读

viewsIcon

71914

downloadIcon

2330

一个带有禁用列表项的自定义列表框控件。

引言

这是一个带有禁用项选项的列表框用户控件。 可以通过您选择的前缀将禁用项标记为禁用,或者通过选择源数据库中列表 DataSource 中的布尔列来标记。

背景

我有一些项目需要一个列表框来显示禁用的项。 VS 附带的 ListBox 没有为列表项公开此属性。 我最终编写了自己的用户控件,该控件具有将某些项标记为禁用的功能。 如果您的应用程序使用数据库并有许多更新数据的用户,并且您希望在无法再使用对象时或如果其他人正在同时处理同一对象时将其标记为禁用,这将非常有用。

使用代码

此解决方案的基础是使用 ListBox 控件中的 DrawMode.OwnerDrawFixed 属性。 我们需要首先创建一个用户控件项目并从 ListBox 继承。 然后,只需在控件的构造函数中添加以下行

this.DrawMode = DrawMode.OwnerDrawFixed; 

这意味着我们控制列表框的绘制方式。

接下来,我们需要重写方法 OnDrawItem(DrawItemEventArgs e)。 此方法执行列表框控件内项的绘制。 在这里,我们选择是否要将该项绘制为禁用状态。

这是使用前缀禁用项的基础代码

string item = this.Items[e.Index].ToString();
//Check if the item is disabled
if (item.StartsWith(prefix))
{
    item = item.Remove(0, prefix.Length);
    myBrush = Brushes.Gray;
}
if (!item.StartsWith(prefix))
{
    // Draw the background of the ListBox control for each item.
    e.DrawBackground();
}
// Draw the current item text based on the current Font and the custom brush settings.
e.Graphics.DrawString(item, e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);

接下来,我们希望启用选择项。

//If the selected item is a disabled item dont select it
if ((e.State & DrawItemState.Selected) == 
     DrawItemState.Selected && item.StartsWith(prefix))
{
    this.SelectedIndex = -1; 
    this.Invalidate();
}
//if the selected item is not disable change the text color to white
else if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
    myBrush = Brushes.White;
    e.Graphics.DrawString(item, e.Font, myBrush, e.Bounds, 
                          StringFormat.GenericDefault);
    e.DrawFocusRectangle();
}
else
{
    if (!item.StartsWith(prefix))
        // If the ListBox has focus, draw a focus
        // rectangle around the selected item.
        e.DrawFocusRectangle();
}

现在,我们必须将该项重新绘制回列表框控件

base.OnDrawItem(e);

在附带的源代码中,您将找到将禁用项连接到数据库中的列的代码。

就这样。尽情享受吧!

关注点

玩转内置控件总是很有趣。 请记住,您可以在 VS 中完成任何事情(几乎)。

© . All rights reserved.