c# - 如何将列表计数绑定(bind)到标签

标签 c# winforms data-binding

我有一个绑定(bind)到列表的 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));
    }
}

但是,这在绑定(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/

相关文章:

c# - 静态方法如何返回它自己的抽象类的对象 - WebRequest

c# - 如何自动生成必须为每个方法编写的代码?

winforms - 是否可以在不使用 ImageList 的情况下将图像添加到 TreeView 节点?

user-interface - Xamarin表单框架未随内容扩展

c# - 在 asp.net 中保留枚举值

c# - 为什么此代码会导致 Excel 无法正常关闭?

c# - 使用户控件内的标签对于所有鼠标事件都可单击?

c# - 打开文件对话框,多个 Excel 扩展的一个过滤器?

c# - 将集合绑定(bind)到列表框

c# - 如何编写自定义模板字段类 DataControlField