如何将列表的计数绑定到标签.更改列表后,以下代码无法更新:
private IList<string> list = new List<string>();
//...
label1.DataBindings.Add("Text", list.Count, "");
Run Code Online (Sandbox Code Playgroud)
根据 Marc Gravell 的说法,对于这个问题,他建议创建一个外观来包装要绑定到 label1.Text 的集合
我尝试实现一个(为了好玩)并且能够绑定到Count工作。
是一个包装要绑定到的集合的外观。CountList<T>
这是完整的演示。
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"));
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5664 次 |
最近记录: |