且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 ArrayList 数据绑定到 VB.NET 中的 ListBox?

更新时间:2021-07-13 02:25:28

我将假设这是 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 是显而易见的选择(ArrayList 根本不会做...)
  • 要检测对象属性的更改,您需要实现INotifyPropertyChanged(通常您可以使用*Changed"模式,但这不受BindingList)
  • 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 by BindingList<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);
        }
    }
}