如何使选中列表框中的项目变灰

Chr*_*fer 2 .net c# windows winforms visual-studio-2012

我有一个检查列表框,显示了许多项目.应禁用该框中的某些项目但可见(取决于几个单选按钮的状态).

我已经能够通过使用ItemCheck事件处理程序禁用它们以便您无法检查或取消选中它们,因此这不是问题.

我现在需要的只是找到一种方法来使项目变灰.我试过这个:

myCheckedListBox.SetItemCheckState(index, CheckState.Indeterminate)
Run Code Online (Sandbox Code Playgroud)

这使项目复选框灰色但是已选中.我需要它是灰色的,要么选中要么取消选中,具体取决于项目的状态.

有没有办法改变CheckedListBox中单个项目的外观

Kin*_*ing 5

你必须CheckedListBox像这样创建自己的:

public class CustomCheckedList : CheckedListBox
{
    public CustomCheckedList()
    {
        DisabledIndices = new List<int>();
        DoubleBuffered = true;
    }
    public List<int> DisabledIndices { get; set; }
    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        base.OnDrawItem(e);
        Size checkSize = CheckBoxRenderer.GetGlyphSize(e.Graphics, System.Windows.Forms.VisualStyles.CheckBoxState.MixedNormal);
        int d = (e.Bounds.Height - checkSize.Height) / 2;                        
        if(DisabledIndices.Contains(e.Index)) CheckBoxRenderer.DrawCheckBox(e.Graphics, new Point(d,e.Bounds.Top + d), GetItemChecked(e.Index) ? System.Windows.Forms.VisualStyles.CheckBoxState.CheckedDisabled : System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedDisabled);
    }
    protected override void OnItemCheck(ItemCheckEventArgs ice)
    {
        base.OnItemCheck(ice);
        if (DisabledIndices.Contains(ice.Index)) ice.NewValue = ice.CurrentValue;
    }
}
//To disable the item at index 0:
customCheckedList.DisableIndices.Add(0);
Run Code Online (Sandbox Code Playgroud)

您可能希望使用其他类型的结构来存储禁用的索引,因为List<>我在我的代码中使用的不正常,它可以包含重复的索引.但那是出于示范目的.我们只需要一种方法来了解应该禁用哪些项目以进行相应的渲染.