按搜索字符串过滤 CollectionViewSource - 绑定到 itemscontrol (WPF MVVM) [英] Filter CollectionViewSource by search string - bound to itemscontrol (WPF MVVM)

查看:20
本文介绍了按搜索字符串过滤 CollectionViewSource - 绑定到 itemscontrol (WPF MVVM)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法过滤 CollectionViewSource 以只显示 ItemsSource 中的游戏,其中Title"包含searchString"?

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

在我的 PosterView 中,我有这个 CVS:

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>

还有这个ItemsControl

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

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

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

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

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

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

这是如何将游戏添加到 ObservableCollection

And here is how games are added to the 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,你也应该在那里过滤它:

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

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

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.

这篇关于按搜索字符串过滤 CollectionViewSource - 绑定到 itemscontrol (WPF MVVM)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆