2

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

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

我现在需要的只是找到一种方法将这些项目变灰。我确实试过这个:

myCheckedListBox.SetItemCheckState(index, CheckState.Indeterminate)

这使项目复选框灰色但选中。我需要它是灰色的,并且选中或未选中,具体取决于项目的状态。

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

4

1 回答 1

5

You have to create your own CheckedListBox like this:

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

You may want to use another type of structure to store disabled indices because the List<> I used in my code is not OK, it can contain duplicated indices. But that's for demonstrative purpose. We just need a way to know which items should be disabled to render accordingly.

于 2013-06-17T10:59:45.087 回答