将项目添加到绑定的WPF ListBox

问题描述:

好吧,这一直是我的头上挠头.我有一个ListBox,我绑定到这样的linq查询:

Ok, this has been a head scratcher for me. I have a ListBox I am binding to a linq query like so:

    private IQueryable<Feed> _feeds;

    public IQueryable<Feed> Feeds
    {
        get
        {
            if (_feeds == null)
            {
                var feedsQuery = from f in _db.Feed orderby f.Title select f;
                _feeds = feedsQuery;
            }
            return _feeds;
        }
    }

    public Options()
    {
        InitializeComponent();
        this.DataContext = Feeds;
    }

(为了记录,我也尝试使用List而不是IQueryable)

(For the record I've also tried List, instead of IQueryable)

一切都很好,我有一个数据绑定表格,可以让您编辑记录,所有这些更改都可以正常工作,修改后的数据显示在列表中.

Everything shows up great and I have a databound form that allows you to edit a record and all of those changes work just fine, the modified data shows up in the list.

问题来自于我添加项目.列表中没有任何内容.数据可以很好地进入数据库,但是查看数据的唯一方法是关闭并重新启动我的应用程序.我以下面的代码为例:

The problem comes with I add an item. Nothing shows up in the list. The data goes into the database fine, but the only way to see the data is closing and restarting my app. I'm using the code below as an example:

        Feed feed = new Feed()
        {
            ID = Guid.NewGuid(),
            Url = "http://www.test.com",
            Title = "Test"
        };
        _db.Feed.InsertOnSubmit(feed);
        _db.SubmitChanges();
        _db.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues);

(使用或不使用_db.Refresh都不会发生)

(with or without the _db.Refresh nothing happens)

这是怎么回事?

您所做的一切正确,您必须使用 ObservableCollection .这将通知ListBox有关列表中的任何更改并自动刷新.

You are doing everything right, you jus need to use ObservableCollection. This will notify the ListBox about any changes in the list and refresh it automatically.

来自MSDN

在许多情况下,您处理的数据 与是对象的集合.为了 例如,数据中的常见场景 绑定是使用ItemsControl 例如ListBox,ListView或 TreeView显示一个集合 记录.

In many cases the data that you work with is a collection of objects. For example, a common scenario in data binding is to use an ItemsControl such as a ListBox, ListView, or TreeView to display a collection of records.

P.S.您不需要数据库刷新

P.S. you don't need a db refresh