CheckedListBox:如何增加复选框的大小并更改刻度线的颜色

时间:2017-09-01 13:20:29

标签: c# winforms desktop-application checkedlistbox

我想覆盖 CheckedListBox 的默认外观,如下所示: Large checkbox in listbox

请注意复选框和彩色刻度标记的大小增加。

1 个答案:

答案 0 :(得分:1)

为此,您需要通过继承CheckedListbox来创建自己的自定义控件,并需要覆盖OnDrawItem(DrawItemEventArgs e)事件

  

以下是代码:

class BigCheckedListBox : CheckedListBox
{
    public BigCheckedListBox()
    {
        ForeColor = Color.Turquoise;
        Font = new Font("Segoe UI", 12f);
    }
    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        e.DrawBackground();

        var b = e.Bounds;
        var state = GetItemChecked(e.Index) ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal;
        Size glyphSize = CheckBoxRenderer.GetGlyphSize(e.Graphics, state);
        int checkPad = (b.Height - glyphSize.Height) / 2;
        var pt = new Point(b.X + checkPad, b.Y + checkPad);

        Rectangle rect = new Rectangle(pt, new Size(20, 20));
        e.Graphics.DrawRectangle(Pens.Green, rect);//This is for Checkbox rectangle

        //This is for drawing string text
        using (SolidBrush brush = new SolidBrush(ForeColor))
            e.Graphics.DrawString(this.Items[e.Index].ToString(), Font, brush, pt.X + 27f, pt.Y); 


        if (state == CheckBoxState.CheckedNormal)
        {
            using (SolidBrush brush = new SolidBrush(ForeColor))
            using (Font wing = new Font("Wingdings", 17f, FontStyle.Bold))
                e.Graphics.DrawString("ü", wing, brush, pt.X-4, pt.Y-1); //This is For tick mark
        }
    }
}

希望这能达到目的。