按搜索字符串过滤 CollectionViewSource - 绑定到 itemscontrol (WPF MVVM)

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

有什么方法可以过滤 CollectionViewSource 以仅显示 ItemsSource 中的游戏,其中 "Title" 包含 "searchString"?

在我的 PosterView 我有这个 CVS:

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

还有这个ItemsControl

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

我的 MainWindow.xaml 包含可以成功将 searchString(包含搜索框中内容的字符串)传递给 PosterView 的搜索框。

PosterView 绑定实际上是(令人困惑,我知道),一个 ObservableCollection

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

下面是如何将游戏添加到 ObservableCollection

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]
});

如果您在视图中创建 CollectionViewSource,您也应该在那里过滤它:

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

另一个选项是绑定到一个 ICollectionView 并在视图模型中过滤这个:

_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(); }
}

或者直接对源集合本身进行排序。