首页 > 解决方案 > DataSource 中的更新重置 CheckedListBox 复选框

问题描述

我有一个 CheckedListBox,绑定到一个 BindingList:

private BindingList<string> list = new BindingList<string>();
public MyForm()
{
    InitializeComponent();

    list.Add("A");
    list.Add("B");
    list.Add("C");
    list.Add("D");

    checkedListBox.DataSource = collection;
}

单击某个按钮时,列表会更新:

private void Button_Click(object sender, EventArgs e)
{
    list.Insert(0, "Hello!");
}

它工作正常,CheckedListBox 已更新。但是,当某些项目被选中时,单击按钮不仅会更新列表,还会重置所有未选中的项目。我该如何解决?

谢谢!

标签: c#winformsdata-bindingcheckedlistbox

解决方案


您需要自己跟踪检查状态。

作为一个选项,您可以为包含文本和检查状态的项目创建模型类。然后在ItemCheck控制事件中,设置项目模型的检查状态值。同样在ListChengedBindingList<T>刷新项目检查状态的情况下。

例子

创建CheckedListBoxItem类:

public class CheckedListBoxItem
{
    public CheckedListBoxItem(string text)
    {
        Text = text;
    }
    public string Text { get; set; }
    public CheckState CheckState { get; set; }
    public override string ToString()
    {
        return Text;
    }
}

像这样设置CheckedListBox

private BindingList<CheckedListBoxItem> list = new BindingList<CheckedListBoxItem>();
private void Form1_Load(object sender, EventArgs e)
{
    list.Add(new CheckedListBoxItem("A"));
    list.Add(new CheckedListBoxItem("B"));
    list.Add(new CheckedListBoxItem("C"));
    list.Add(new CheckedListBoxItem("D"));
    checkedListBox1.DataSource = list;
    checkedListBox1.ItemCheck += CheckedListBox1_ItemCheck;
    list.ListChanged += List_ListChanged;
}
private void CheckedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
    ((CheckedListBoxItem)checkedListBox1.Items[e.Index]).CheckState = e.NewValue;
}
private void List_ListChanged(object sender, ListChangedEventArgs e)
{
    for (var i = 0; i < checkedListBox1.Items.Count; i++)
    {
        checkedListBox1.SetItemCheckState(i,
            ((CheckedListBoxItem)checkedListBox1.Items[i]).CheckState);
    }
}

推荐阅读