如何将列表计数绑定到标签

时间:2013-05-21 01:41:57

标签: c# winforms data-binding

我有一个DataGridView绑定到列表和一个标签显示记录数。我遇到了同样的问题Khash。 (所以我偷了他的头衔)。网格上的任何添加或删除操作都不会更新标签。

enter image description here

根据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));
    }
}

但是,这会在绑定时抛出异常。

Cannot bind to the property or column Count on the DataSource. Parameter name: dataMember

以下是我的绑定代码:

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; }
}

任何建议将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:5)

事实上,它比你想象的要简单得多!

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);
    }