我正在尝试绘制或更改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.
}
}
有没有办法单独更改文字?
答案 0 :(得分:2)
您不需要任何绘图。您可以创建包含Item
和Value
属性的类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";