IBindingList And IBindingListView
How can it be?
List<T>
doesn't implement IBindingList
/ IBindingListView
- 开发者_C百科thus it cannot provide UI updates. You are going to need to change a few bits of code to suit the BindigList api.
UI notifications are done typically via events. This means, in this case, IBindingList and the ListChanged
event; but also some side interfaces like IBindingListView, and a few other optional things for improved list adding etc. BindingList<T>
supports pretty much everything you need, but as a consequence has some small overheads.
By contrast, List<T>
deliberately provides none of this; it is a general purpose (and fast) dynamic list device, not an "observer" device.
Note you also typically need your type T
to implement INotifyPropertyChanged if you want cell-by-cell updates; without this you can only get row-level updates (add, remove, etc).
For example:
using System;
using System.ComponentModel;
using System.Windows.Forms;
static class Program
{
class Foo
{
public int A { get; set; }
public string B { get; set; }
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (var form = new Form())
using (var grid = new DataGridView { Dock = DockStyle.Fill })
using (var add = new Button { Dock = DockStyle.Bottom, Text = "add" })
using (var remove = new Button { Dock = DockStyle.Top, Text = "remove" })
{
form.Controls.Add(grid);
form.Controls.Add(add);
form.Controls.Add(remove);
var lst = new BindingList<Foo>();
var rnd = new Random();
add.Click += delegate
{
lst.Add(new Foo { A = rnd.Next(1, 6), B = "new" });
};
remove.Click += delegate
{
int index = 0;
foreach (var row in lst)
{ // just to illustrate removing a row by predicate
if (row.A == 2) { lst.RemoveAt(index); break; }
index++;
}
};
grid.DataSource = lst;
Application.Run(form);
}
}
}
精彩评论