我有一个绑定(bind)到列表的 DataGridView 和一个显示记录数的标签。我遇到了同样的问题Khash有。 (所以我窃取了他的头衔)。网格上的任何添加或删除操作都不会更新标签。
基于Sung's answer, a facade wrapper ,我创建了继承 BindingList
并实现 INotifyPropertyChanged
的自定义列表。
public class CountList<T> : BindingList<T>, INotifyPropertyChanged
{
protected override void InsertItem(int index, T item)
{
base.InsertItem(index, item);
OnPropertyChanged("Count");
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
OnPropertyChanged("Count");
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
但是,这在绑定(bind)时会抛出异常。
无法绑定(bind)到数据源上的属性或列计数。
参数名称:dataMember
下面是我的绑定(bind)代码:
private CountList<Person> _list;
private void Form1_Load(object sender, EventArgs e)
{
_list = new CountList<Person>();
var binding = new Binding("Text", _list, "Count");
binding.Format += (sender2, e2) => e2.Value = string.Format("{0} items", e2.Value);
label1.DataBindings.Add(binding);
dataGridView1.DataSource = _list;
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
如有任何建议,我们将不胜感激。谢谢。
最佳答案
事实上,它比你想象的要简单得多!
Microsoft 已经创建了 BindingSource 控件,因此,您需要使用它,然后处理 BindingSource 事件来更新标签:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
private BindingSource source = new BindingSource();
private void Form1_Load(object sender, EventArgs e)
{
var items = new List<Person>();
items.Add(new Person() { Id = 1, Name = "Gabriel" });
items.Add(new Person() { Id = 2, Name = "John" });
items.Add(new Person() { Id = 3, Name = "Mike" });
source.DataSource = items;
gridControl.DataSource = source;
source.ListChanged += source_ListChanged;
}
void source_ListChanged(object sender, ListChangedEventArgs e)
{
label1.Text = String.Format("{0} items", source.List.Count);
}
关于c# - 如何将列表计数绑定(bind)到标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16660875/