c# - 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 已更新。但是,当某些项目被选中时,单击按钮不仅会更新列表,还会重置所有未选中的项目。我该如何解决?
谢谢!
解决方案
您需要自己跟踪检查状态。
作为一个选项,您可以为包含文本和检查状态的项目创建模型类。然后在ItemCheck
控制事件中,设置项目模型的检查状态值。同样在ListChenged
您BindingList<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);
}
}
推荐阅读
- c# - 单击 X 后从 UserControl 访问值
- r - R中变量的复杂分离
- java - 在带有 Gradle 的 JavaExec 类路径中使用通配符
- java - FloatBuffer 占用越来越多的 RAM
- php - 我目前无法停止通过 ajax 调用在服务网页上播放音频
- sql - 如何用最大值标记行
- grails - 如何在 Linux(Ubuntu 18.04.1 LTS)上修复 Grails 2.4.4“错误:交互模式退出并出现错误”
- javascript - Krajee Bootstrap 文件输入无法通过大文件传递uploadExtraData
- python - 在两个远程服务器之间传输文件(在本地启动连接)
- javascript - 如何使用 AmCharts 构建曲线股票图表