How can I execute WPF filters on a background thre

2019-05-10 20:57发布

I'm using filters in WPF and I'm following the pattern suggested here.

To summarize, this involves a text property being exposed on the ViewModel which represents the text to filter by. When the property is set (by the binding from the textbox in the View) it uses CollectionViewSource.GetDefaultView(MyItems).Filter = blah to filter the visible list of items.

This works great, but the problem comes when the collection of items is very large, as the filtering is performed on the foreground thread and thus hangs the UI. Does there exist a pattern for performing filtering on a background thread, and how does this fit in the Model-View-ViewModel pattern?

1条回答
一夜七次
2楼-- · 2019-05-10 21:31

Instead of using CollectionView for filtering, do your own: In your ViewModel create a property that contains the filtered data and one to hold the filter. Whenever the filter is changed, fire off a work item in a separate thread to computed the new filtered data property then update that property when it is done. When updating the property, either update the existing collection or replace it depending on how many changes were made.

I use a class I use that automates this so it is as easy as declaring the one collection to be a filtered version of the other.

查看更多
登录 后发表回答