我在 VB.NET 工作
我有一个名为 Invoices 的 ArrayList,其中填充了 Invoice 类的对象。
我想将其数据绑定到 ListBox,以便随着 ArrayList 的内容更新并更改 ListBox 的更新。我已经在 Invoice 类上实现了 .ToString 函数,我只是不知道如何将 ArrayList 绑定到 ListBox。
有什么建议么?
我将假设这是 winforms。
如果你想要双向数据绑定,你需要一些东西:
- 要检测添加/删除等,您需要一个实现的数据源
IBindingList
;对于课程,BindingList<T>
是显而易见的选择(ArrayList
根本不会做...)
- 检测变化特性的对象,你需要实现
INotifyPropertyChanged
(通常您可以使用“*Changed”模式,但这不被尊重BindingList<T>
)
幸运的是,ListBox
处理这两件事。完整的例子如下:我使用过 C#,但概念是相同的......
using System;
using System.ComponentModel;
using System.Windows.Forms;
class Data : INotifyPropertyChanged{
private string name;
public string Name
{
get { return name; }
set { name = value; OnPropertyChanged("Name"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this,
new PropertyChangedEventArgs(propertyName));
}
}
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Button btn1, btn2;
BindingList<Data> list = new BindingList<Data> {
new Data { Name = "Fred"},
new Data { Name = "Barney"},
};
using (Form frm = new Form
{
Controls =
{
new ListBox { DataSource = list, DisplayMember = "Name",
Dock = DockStyle.Fill},
(btn1 = new Button { Text = "add", Dock = DockStyle.Bottom}),
(btn2 = new Button { Text = "edit", Dock = DockStyle.Bottom}),
}
})
{
btn1.Click += delegate { list.Add(new Data { Name = "Betty" }); };
btn2.Click += delegate { list[0].Name = "Wilma"; };
Application.Run(frm);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)