如何将列表的计数绑定(bind)到标签。以下代码不会随着列表的更改而更新:

private IList<string> list = new List<string>();
//...
label1.DataBindings.Add("Text", list.Count, "");

最佳答案

根据Marc Gravell对于此问题的说法,他具有suggested to create a facade,该包装将要绑定(bind)到label1.Text的集合。

我尝试实现一个(很有趣),并且能够绑定(bind)到Count工作。CountList<T>是包装要绑定(bind)到的集合的外观。

这是完整的演示。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace TextBindingTest
{
    public partial class Form1 : Form
    {
        private readonly CountList<string> _List =
            new CountList<string>(new List<string> { "a", "b", "c" });

        public Form1()
        {
            InitializeComponent();
            BindAll();
        }

        private void BindAll()
        {
            var binding = new Binding("Text", _List, "Count", true);
            binding.Format += (sender, e) => e.Value = string.Format("{0} items", e.Value);
            label1.DataBindings.Add(binding);
        }

        private void addToList_Click(object sender, EventArgs e)
        {
            _List.Add("a");
        }

        private void closeButton_Click(object sender, EventArgs e)
        {
            Close();
        }
    }

    public class CountList<T> : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged = delegate { };
        private void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            var handler = PropertyChanged;
            handler(this, e);
        }

        private ICollection<T> List { get; set; }
        public int Count { get { return List.Count; } }

        public CountList(ICollection<T> list)
        {
            List = list;
        }

        public void Add(T item)
        {
            List.Add(item);
            OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        }
    }
}

关于c# - 如何将列表计数绑定(bind)到WinForms中的标签?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/639894/

10-13 06:23
查看更多