【问题标题】:Filter CollectionViewSource by search string - bound to itemscontrol (WPF MVVM)按搜索字符串过滤 CollectionViewSource - 绑定到 itemscontrol (WPF MVVM)
【发布时间】:2018-10-24 14:07:07
【问题描述】:

有没有办法可以过滤 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 包含可以成功将 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]
});

【问题讨论】:

    标签: c# wpf xaml mvvm collectionviewsource


    【解决方案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(); }
    }
    

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

    【讨论】:

    • 在第一个解决方案(PosterView.xaml.cs 的代码隐藏)中,我将在哪里提取“txtSearchString.Text”,或者如何从 PosterView.xaml.cs 中的另一个方法传入 searchString?由于搜索框在 MainWindow.xaml 中,我需要将 searchString 放入此方法中,对吗?
    • @PeteKemp:来自名为“txtSearchString”的搜索框。视图中有一个搜索框,不是吗?
    • 抱歉,MainWindow.xaml 有搜索框,不过我可以将变量放入 PosterView 中的方法中。搜索框在解决方案的“标题栏”中
    • 那么MainWindow和PosterView是什么关系呢?什么是海报视图?
    • mainwindow 是不同用户控件、posterview、bannerview、listview 的容器
    猜你喜欢
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 2014-08-02
    • 2011-10-20
    • 2010-11-20
    • 1970-01-01
    相关资源
    最近更新 更多