I have a list with 10 million items, and I want to search through the items like an auto completion on a TextBox
, but when I press a key it takes forever for the collectionViewSource
filter to return. How can I do the filtering/refreshing process inside a Thread
or a BackgroundWorker
?
UI:
<Window
x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="350" Width="525">
<Grid>
<TextBox TextChanged="txtSearch_OnTextChanged"/>
<ListBox ItemsSource="{Binding MyCollection}" >
</Grid>
</Window>
Code Behind:
private string _filterString;
public string FilterString
{
get => _filterString;
set
{
_filterString = value;
NotifyPropertyChanged("FilterString");
_myCollection.Refresh();
}
}
private ICollectionView _myCollection;
public ICollectionView MyCollection
{
get => _myCollection;
set
{
_myCollection = value;
NotifyPropertyChanged("MyCollection");
}
}
MyCollection = CollectionViewSource.GetDefaultView(db.GetSampleCollection());
MyCollection.Filter = FilterResult;
public bool FilterResult(object obj)
{
var words = obj as List<string>;
return words.AsParallel().Any(t => t.Contains(_filterString));
}
private async void txtSearch_OnTextChanged(object sender, TextChangedEventArgs e)
{
FilterString = txtSearch.Text;
}