[英]Trying to Bind List<T> to CheckedListBox in WinForms c#
I am using WinForms C# Is there any way to get following behavior:我正在使用 WinForms C# 有没有办法获得以下行为:
I tried to do the following:我尝试执行以下操作:
Constructor code:构造函数代码:
checkedlistBox1.DataSource = a;
checkedlistBox1.DisplayMember = "Name";
checkedlistBox1.ValueMember = "Name";
Field:场地:
List<Binder> a = new List<Binder> { new Binder { Name = "A" } };
On button1 click:在按钮 1 上单击:
private void butto1_Click(object sender, EventArgs e)
{
a.Add(new Binder{Name = "B"});
checkedListBox1.Invalidate();
checkedListBox1.Update();
}
But the view does not update .但视图不会更新。
Thank You.谢谢。
Change this line:改变这一行:
List<Binder> a = new List<Binder> { new Binder { Name = "A" } };
to this:对此:
BindingList<Binder> a = new BindingList<Binder> { new Binder { Name = "A" } };
It will just work without any other changes.它将在没有任何其他更改的情况下工作。
The key is that BindingList<T>
implements IBindingList
, which will notify the control when the list changes.关键是
BindingList<T>
实现了IBindingList
,它会在列表发生变化时通知控件。 This allows the CheckedListBox control to update its state.这允许 CheckedListBox 控件更新其状态。 This is two-way data binding.
这是双向数据绑定。
Also, you could change these two lines:此外,您可以更改这两行:
checkedListBox1.Invalidate();
checkedListBox1.Update();
to this (more readable and essentially does the same thing):对此(更具可读性并且基本上做同样的事情):
checkedListBox1.Refresh();
Two things you may wish to look at:您可能希望查看两件事:
您的List<Bender>
是否需要成为某种可观察的集合,例如ObservableCollection<Bender>
?
The proper way of binding a checked listbox is:绑定选中列表框的正确方法是:
List<YourType> data = new List<YourType>();
checkedListBox1.DataSource = new BindingList<YourType>(data);
checkedListBox1.DisplayMember = nameof(YourType.Name);
checkedListBox1.ValueMember = nameof(YourType.ID);
Note to self.注意自我。
The issue i have every time binding it is that the properties DataSource , DisplayMember and ValueMember are not suggested by intellisense and i get confused.我每次绑定时遇到的问题是智能感知不建议属性DataSource 、 DisplayMember和ValueMember ,我感到困惑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.