Search code examples
c#winformschecklistbox

Custom CheckListBox Honor 2 columns


I created a custom checklistbox so I could change the foreground color of certain items however when I enable the MutiColumn to true the values overlap each other rather than working in multiple columns..

public sealed class CustomCheckedListBox : CheckedListBox
{
    public CustomCheckedListBox()
    {
        DoubleBuffered = true;
    }

    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        Size checkSize = CheckBoxRenderer.GetGlyphSize(e.Graphics,
            System.Windows.Forms.VisualStyles.CheckBoxState.MixedNormal);
        int dx = (e.Bounds.Height - checkSize.Width)/2;
        e.DrawBackground();
        bool isChecked = GetItemChecked(e.Index); //For some reason e.State doesn't work so we have to do this instead.
        CheckBoxRenderer.DrawCheckBox(e.Graphics, new Point(dx, e.Bounds.Top + dx),
            isChecked
                ? System.Windows.Forms.VisualStyles.CheckBoxState.CheckedNormal
                : System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal);
        using (StringFormat sf = new StringFormat {LineAlignment = StringAlignment.Center})
        {
            using (Brush brush = new SolidBrush(isChecked ? CheckedItemColor : BackColor))
            {
                e.Graphics.DrawString(Items[e.Index].ToString(), Font, brush,
                    new Rectangle(e.Bounds.Height, e.Bounds.Top, e.Bounds.Width - e.Bounds.Height, e.Bounds.Height), sf);
            }
        }
    }

    private Color _checkedItemColor = Color.Blue;

    public Color CheckedItemColor
    {
        get { return _checkedItemColor; }
        set
        {
            _checkedItemColor = value;
            Invalidate();
        }
    }
}

Can anyone suggest any changes that need to be made in order to have this not happen?


Solution

  • Your rectangle coordinates are not accurate. Also, controls use the TextRenderer class to draw text:

    protected override void OnDrawItem(DrawItemEventArgs e) {
      e.DrawBackground();
      bool isChecked = GetItemChecked(e.Index);
      Size checkSize = CheckBoxRenderer.GetGlyphSize(e.Graphics, CheckBoxState.MixedNormal);
    
      CheckBoxRenderer.DrawCheckBox(e.Graphics,
        new Point(e.Bounds.Left + 2,
                  e.Bounds.Top + (e.Bounds.Height / 2) - (checkSize.Height / 2)),
        isChecked ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal);
    
      TextRenderer.DrawText(e.Graphics, Items[e.Index].ToString(), Font,
        new Rectangle(e.Bounds.Left + checkSize.Width + 3, e.Bounds.Top,
                      e.Bounds.Width - (checkSize.Width + 3), e.Bounds.Height - 1),
        isChecked ? CheckedItemColor : ForeColor, Color.Empty, TextFormatFlags.VerticalCenter);
    }