微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 将列表绑定到DataSource

我希望能够将列表绑定到列表框数据源,并且在修改列表时,列表框的UI会自动更新. ( Winforms不是ASP).
这是一个示例:
private List<Foo> fooList = new List<Foo>();

    private void Form1_Load(object sender,EventArgs e)
    {
        //Add first Foo in fooList
        Foo foo1 = new Foo("bar1");
        fooList.Add(foo1);

        //Bind fooList to the listBox
        listBox1.DataSource = fooList;
        //I can see bar1 in the listBox as expected
    }

    private void button1_Click(object sender,EventArgs e)
    {
        //Add anthoter Foo in fooList
        Foo foo2 = new Foo("bar2");
        fooList.Add(foo2);
        //I expect the listBox UI to be updated thanks to INotifyPropertyChanged,but it's not
    }

class Foo : INotifyPropertyChanged
{
    private string bar_ ;
    public string Bar
    {
        get { return bar_; }
        set 
        { 
            bar_ = value;
            NotifyPropertyChanged("Bar");
        }
    }

    public Foo(string bar)
    {
        this.Bar = bar;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this,new PropertyChangedEventArgs(info));
        }
    }

    public override string ToString()
    {
        return bar_;
    }
}

如果我替换List< Foo> fooList = new List< Foo>();通过BindingList< Foo> fooList = new BindingList< Foo>();然后它工作.但我不想改变原来的傻瓜式.我希望这样的工作:listBox1.DataSource = new BindingList< Foo>(fooList);

编辑:我还在这里阅读来自Ilia Jerebtsov的List<T> vs BindingList<T> Advantages/DisAdvantages:“当你将BindingSource的DataSource设置为List<>时,它会在内部创建一个BindingList来包装你的列表”.我想我的样本只是证明了这不是真的:我的列表<>似乎没有内部包装到BindingList<>中.

解决方法

你的例子中没有 BindingSource.

您需要像这样修改它以使用BindingSource

var bs = new BindingSource();
   Foo foo1 = new Foo("bar1");
   fooList.Add(foo1);

     bs.DataSource = fooList; //<-- point of interrest

    //Bind fooList to the listBox
    listBox1.DataSource = bs; //<-- notes it takes the entire bindingSource

编辑

请注意(正如评论中指出的那样) – bindingsource不能与INotifyPropertyChanged一起使用

原文地址:https://www.jb51.cc/csharp/100942.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐