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

Pet*_*emp 2 c# wpf xaml mvvm collectionviewsource

有没有办法可以过滤CollectionViewSource只显示ItemsSource“标题”包含“搜索字符串”的游戏?

在我的PosterView我有这个 CVS:

<CollectionViewSource x:Key="GameListCVS"
                      Source="{Binding PosterView}"
                      Filter="GameSearchFilter">
    <CollectionViewSource.SortDescriptions>
        <scm:SortDescription PropertyName="Title" />
    </CollectionViewSource.SortDescriptions>
</CollectionViewSource>
Run Code Online (Sandbox Code Playgroud)

还有这个 ItemsControl

<ItemsControl x:Name="gameListView"
              ItemsSource="{Binding Source={StaticResource GameListCVS}}">
Run Code Online (Sandbox Code Playgroud)

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

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

public ObservableCollection<GameList> PosterView { get; set; }
Run Code Online (Sandbox Code Playgroud)

以下是将游戏添加到 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]
});
Run Code Online (Sandbox Code Playgroud)

mm8*_*mm8 5

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

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

另一种选择是绑定到一个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(); }
}
Run Code Online (Sandbox Code Playgroud)

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