数据绑定一个ArrayList VB.NET中一个ListBox? [英] Databinding an ArrayList to a ListBox in VB.NET?
问题描述
我在VB.NET工作
我有填充类发票的对象一个ArrayList名为发票。
I have an ArrayList named Invoices populated with objects of the class Invoice.
我想将数据绑定这一个列表框,这样为ArrayList的内容更新,改变了列表框更新。我实现了对发票类的ToString功能,我只是不知道我怎么会去了解的ArrayList绑定到ListBox。
I'd like to data bind this to a ListBox so that as the contents of the ArrayList are updated and changed the ListBox updates. I've implemented a .ToString function on the Invoice class, I just don't know how I'd go about binding the ArrayList to the ListBox.
有什么建议?
推荐答案
我要作一个假设,这是的WinForms。
I'm going to make the assumption that this is winforms.
如果你想双向数据绑定,你需要几件事情:
If you want two-way data-binding, you need a few things:
- 来检测添加/删除等,你需要一个数据源,实现
IBindingList的
;上课,的BindingList< T>
是显而易见的选择(的ArrayList
根本不会做......) - 要检测更改为性质的对象,您需要执行
INotifyPropertyChanged的
(通常你可以使用*更改的格局,但这不是由德高望重的的BindingList< T>
)
- to detect addition/removal etc, you need a data-source that implements
IBindingList
; for classes,BindingList<T>
is the obvious choice (ArrayList
simply won't do...) - to detect changes to properties of the objects, you need to implement
INotifyPropertyChanged
(normally you can use the "*Changed" pattern, but this isn't respected byBindingList<T>
)
幸运的是,的ListBox
处理这两种。一个完整的示例如下:我使用C#,但其概念是一样的...
Fortunately, ListBox
handles both of these. A full example follows; I've used C#, but the concepts are identical...
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);
}
}
}
这篇关于数据绑定一个ArrayList VB.NET中一个ListBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!