简体   繁体   English

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

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

Is there a way I can filter the CollectionViewSource to only show games in the ItemsSource which "Title" contains the "searchString"?有没有办法可以过滤CollectionViewSource以仅显示“标题”包含“searchString”的ItemsSource中的游戏?

In my PosterView I have this CVS:在我的PosterView我有这个 CVS:

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

and also this ItemsControl还有这个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 .我MainWindow.xaml包含了搜索框,可以顺利通过搜索字符串(含是什么在搜索框中输入字符串) PosterView

PosterView binding is actually (confusingly, I know), an ObservableCollection PosterView绑定实际上是(令人困惑,我知道),一个ObservableCollection

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

And here is how games are added to the ObservableCollection以下是将游戏添加到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]
});

If you are creating the CollectionViewSource in the view, you should filter it there as well:如果你在视图中创建CollectionViewSource ,你也应该在那里过滤它:

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:另一种选择是绑定到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(); }
}

Or sort the source collection itself directly.或者直接对源集合本身进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM