过滤一个ObservableCollection? [英] Filtering an ObservableCollection?
问题描述
当我直接绑定一个ListBox到一个ObservableCollection我得到了我的列表框显示的实时更新,但只要我在混合添加其他LINQ方法我的列表框不再是任何改变的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.
下面,让我说明一个例子;
Here, let me illustrate with an example;
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());
}
}
在这里,我添加了一个按钮和一个列表框,以一个简单的页面,然后点击按钮,使新项目在ListBox中立即出现。
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和列表框之间,仍然得到它,而无需重新设置.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屋!