How change the color of SelectedItem in CheckedListBox in WindowsForms?

后端 未结 2 1205
暗喜
暗喜 2021-01-18 16:28

I want to change the color of the items that are chedked in the CheckedListBox in C# WindowsForms.

Can any one help me to solve this problem!

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-18 16:52

    This should get you started. I've subclassed a CheckedListBox and overridden the drawing event. The result is all checked items in the list are drawn with a red background.

    From playing around with this, if you want the area behind the checkbox to be a different colour as well, use e.Graphics.FillRectangle before calling base.OnDrawItem.

    class ColouredCheckedListBox : CheckedListBox
    {
        protected override void OnDrawItem(DrawItemEventArgs e)
        {
            DrawItemEventArgs e2 =
                new DrawItemEventArgs
                (
                    e.Graphics,
                    e.Font,
                    new Rectangle(e.Bounds.Location, e.Bounds.Size),
                    e.Index,
                    e.State,
                    e.ForeColor,
                    this.CheckedIndices.Contains(e.Index) ? Color.Red : SystemColors.Window
                );
    
            base.OnDrawItem(e2);
        }
    }
    

提交回复
热议问题