我对以 win 形式绑定(bind)比较陌生。为了学习这个主题,我设置了以下测试应用程序。带有 ListBox
和 Button
的基本 winform。
public partial class Form1 : Form
{
public List<String> stringList = new List<String>();
public Form1()
{
InitializeComponent();
stringList.Add("First");
listBox1.DataSource = stringList;
}
private void button1_Click(object sender, EventArgs e)
{
stringList.Add("Second");
}
}
字符串“First”在应用程序启动时显示在 listBox1
中。但是,当我按下向 stringList
添加新字符串的按钮时,新项目未显示在 listBox1
中。谁能帮助我了解集合数据绑定(bind)的基础知识?
最佳答案
替换List<String>
与 BindingList<String>
.
BindingList class可以用作创建双向数据绑定(bind)机制的基类。 BindingList 提供了 IBindingList 接口(interface)的具体、通用的实现。
List<T>
类不提供有关集合更改的任何通知。所以没办法ListBox
会知道添加了一个新元素。但是,如果您使用实现了 IBindingList Interface 的集合, ListBox 订阅 ListChanged
事件。这就是它知道何时刷新自身的方式。
关于c# - Winforms绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6367540/