-->

通过搜索字符串过滤CollectionViewSource - 绑定到ItemsControl的(

2019-09-29 09:20发布

有没有一种方法,我可以过滤CollectionViewSource只秀场中,“标题”包含“搜索字符串”中的ItemsSource?

在我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包含了搜索框,可以顺利通过搜索字符串(含是什么在搜索框中输入字符串)PosterView。

PosterView结合实际(容易混淆的,我知道),一个ObservableCollection

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

这里是游戏如何添加到观察集合

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

Answer 1:

如果你正在创建的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(); }
}

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



文章来源: Filter CollectionViewSource by search string - bound to itemscontrol (WPF MVVM)