Filter CollectionViewSource by search string - bound to itemscontrol (WPF MVVM)

巧了我就是萌 提交于 2019-12-11 08:04:02

问题


Is there a way I can filter the CollectionViewSource to only show games in the ItemsSource which "Title" contains the "searchString"?

In my PosterView I have this CVS:

    <CollectionViewSource x:Key="GameListCVS"
                          Source="{Binding PosterView}"
                          Filter="GameSearchFilter">
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="Title" />
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>

and also this ItemsControl

    <ItemsControl x:Name="gameListView"
                      ItemsSource="{Binding Source={StaticResource GameListCVS}}">

My MainWindow.xaml contains the search box which can successfully pass the searchString (string containing what is in the search box) to PosterView.

PosterView binding is actually (confusingly, I know), an ObservableCollection

 public ObservableCollection<GameList> PosterView { get; set; }

And here is how games are added to the Observable Collection

                    games.Add(new GameList
                {
                    Title = columns[0],
                    Genre = columns[1],
                    Path = columns[2],
                    Link = columns[3],
                    Icon = columns[4],
                    Poster = columns[5],
                    Banner = columns[6],
                    Guid = columns[7]
                });

回答1:


If you are creating the CollectionViewSource in the view, you should filter it there as well:

private void GameSearchFilter(object sender, FilterEventArgs e)
{
    GameList game = e.Item as GameList;
    e.Accepted = game != null && game.Title?.Contains(txtSearchString.Text);
}

The other option would be to bind to an ICollectionView and filter this one in the view model:

_view = CollectionViewSource.GetDefaultView(sourceCollection);
_view.Filter = (obj) => 
{
    GameList game = obj as GameList;
    return game != null && game.Title?.Contains(_searchString);
};
...
public string SearchString
{
    ...
    set { _searchString = value; _view.Refresh(); }
}

Or sort the source collection itself directly.



来源:https://stackoverflow.com/questions/52971092/filter-collectionviewsource-by-search-string-bound-to-itemscontrol-wpf-mvvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!