简体   繁体   English

尝试绑定列表<T>到 WinForms c# 中的 CheckedListBox

[英]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# 有没有办法获得以下行为:

  1. bind List to CheckedListBox将列表绑定到 CheckedListBox
  2. When I add elements to list CheckedList box refereshes当我将元素添加到列表 CheckedList 框时
  3. When I change CheckedListBox the list changes当我更改 CheckedListBox 列表更改

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:您可能希望查看两件事:

  1. Use a BindingList使用绑定列表
  2. Add a BindableAttribute to your Name propertyBindableAttribute添加到您的Name属性

您的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.我每次绑定时遇到的问题是智能感知不建议属性DataSourceDisplayMemberValueMember ,我感到困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM