如何在CheckedBoxList控件中的项目上绘制字符串?

时间:2016-05-27 10:23:25

标签: c# windows winforms

我正在尝试绘制或更改CheckedListBox控件中项目的字符串。所以我创建了自CheckedListBox派生的自定义控件。

public class CheckedListBoxAdv : CheckedListBox
{
    public CheckedListBoxAdv()
        :base()
    { 
    }

    protected override void OnDrawItem(DrawItemEventArgs e)
    {
         base.OnDrawItem(e);
        //I want to change the text alone this place. But I cannot access the text part of the item.

    }        
}

有没有办法单独更改文字?

2 个答案:

答案 0 :(得分:2)

您不需要任何绘图。您可以创建包含ItemValue属性的类Name,然后覆盖ToString()类的方法,以返回您需要在CheckedListBox中显示的内容:

public class Item
{
    public int Value { get; set; }
    public string Name { get; set; }
    public override string ToString()
    {
        return this.Name;
    }
}

这样您就可以用CheckedListBox填充项目。它显示Name属性,但您也可以访问Value属性:

private void Form1_Load(object sender, EventArgs e)
{
    this.checkedListBox1.Items.Clear();

    this.checkedListBox1.Items.Add(new Item() { Value = 1, Name = "One" });
    this.checkedListBox1.Items.Add(new Item() { Value = 2, Name = "two" });
    this.checkedListBox1.Items.Add(new Item() { Value = 3, Name = "three" });

    //Change the Name of item at index 1 (2,"two")
    ((Item)this.checkedListBox1.Items[1]).Name = "Some Text";

    //But the value is untouched
    MessageBox.Show(((Item)this.checkedListBox1.Items[1]).Value.ToString());

}

答案 1 :(得分:0)

try this.checkedListBoxName.Items:checkedListBoxName是checkedListBox的名称

例如:this.checkedListBoxName.Items[0] = "abc";