一个禁用条目的列表框

介绍 这是一个列表框用户控件,带有禁用项的选项。禁用项可以使用您选择的前缀标记为禁用,也可以通过为列表数据源选择源数据库中的布尔列来标记。 背景 我有一些项目,我需要一个列表框来显示禁用项目。VS附带的列表框不公开列表框项的这个属性。最后,我编写了自己的用户控件,能够将一些项标记为禁用。如果你有一个应用程序,该应用程序使用一个数据库更新数据有许多用户,你想一个对象标记为禁用如果你不能使用它,或假如说,一些人正在同一个对象。 使用的代码 此解决方案的基础是使用DrawMode。ListBox控件中的OwnerDrawFixed属性。我们需要先创建一个UserControl项目并从ListBox继承。然后,只需在控件的构造函数中添加以下一行: 隐藏,复制Code

this.DrawMode = DrawMode.OwnerDrawFixed; 

这意味着我们可以控制列表框的绘制方式。 接下来,我们需要重写方法OnDrawItem(DrawItemEventArgs e),该方法绘制列表框控件内的项目。在这里,我们选择是否要将项目绘制为禁用。 这是禁用条目库的代码,使用了禁用条目的前缀: 隐藏,复制Code

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);

接下来,我们要启用选择项。 隐藏,复制Code

//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();
}

现在,我们必须把项目拉回listbox控件: 隐藏,复制Code

base.OnDrawItem(e);

在附加的源代码中,您将找到用于将禁用的项连接到数据库中的列的代码。 就是这样。享受吧! 的兴趣点 使用内置控件总是很有趣的。记住,你可以(几乎)在VS中做任何你想做的事情。 本文转载于:http://www.diyabc.com/frontweb/news239.html

原文地址:https://www.cnblogs.com/Dincat/p/13431332.html