过滤 ObservableCollection? [英] Filtering an ObservableCollection?

查看:41
本文介绍了过滤 ObservableCollection?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将 ListBox 直接绑定到 ObservableCollection 时,我会在我的 ListBox 中获得实时更新,但是一旦我在混合中添加其他 LINQ 方法,我的 ListBox 就不再收到 ObservableCollection 的任何更改通知.

When I bind a ListBox directly to an ObservableCollection I get the real-time updates displayed in my ListBox, but as soon as I add other LINQ methods in the mix my ListBox is no longer notified of any changes to the ObservableCollection.

这里我举个例子;

public partial class MainPage : PhoneApplicationPage
{
    ObservableCollection<String> Words = new ObservableCollection<string>();

    public MainPage()
    {
        InitializeComponent();
        listBox1.ItemsSource = Words;
    }

    private void AddButton_Click(object sender, RoutedEventArgs e)
    {
        Words.Add(DateTime.Now.ToString());
    }
}

在这里,我向一个简单的页面添加了一个按钮和一个列表框,单击按钮使新项目立即出现在列表框中.

Here I've added a Button and a ListBox to a simple Page, and clicking the button makes the new item appear immediately in the ListBox.

但是,如果我改变了

        listBox1.ItemsSource = Words;

        listBox1.ItemsSource = Words.Where(w => w.Contains(":"));

ListBox 不再更新.

the ListBox is no longer updated.

如何在我的 ObservableCollection 和 ListBox 之间添加一个过滤器",并且仍然让它更新而无需再次设置 .ItemsSource?

How can I add a "filter" between my ObservableCollection and the ListBox, and still get it to update without having to set the .ItemsSource again?

推荐答案

尝试像这样使用 CollectionViewSource:

Try using the CollectionViewSource like this:

WordsView = new CollectionViewSource();
WordsView.Filter += Words_Filter;
WordsView.Source = Words;

// ...
void Words_Filter(object sender, FilterEventArgs e)
{
    if (e.Item != null)
        e.Accepted = ((string)e.Item).Contains(":");
}

这篇关于过滤 ObservableCollection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆