3

我在 VB.NET 中工作

我有一个名为 Invoices 的 ArrayList,其中填充了 Invoice 类的对象。

我想将它数据绑定到 ListBox,以便更新 ArrayList 的内容并更改 ListBox 更新。我已经在 Invoice 类上实现了一个 .ToString 函数,我只是不知道如何将 ArrayList 绑定到 ListBox。

有什么建议么?

4

1 回答 1

2

我将假设这是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);
        }
    }
}
于 2009-08-17T20:50:09.627 回答