您可以在 UWP 应用程序中过滤 ICollectionView 吗?

Can you filter an ICollectionView in an UWP app?

我仍在通过开发小型 UWP 应用来学习 C#。 基本上我的应用程序获取我拥有的 Steam 游戏并将它们异步添加到 ObservableCollection。它将游戏添加到 Gridview。

XAML:

<GridView
    x:Name="BasicGridView"
    ItemsSource="{Binding}"
    ItemTemplate="{StaticResource ImageTemplate}"
    IsItemClickEnabled="True"
    ItemClick="BasicGridView_ItemClick"
    SelectionMode="Single"
    Margin="15, 0, 0, 0"
>
    <GridView.ItemContainerStyle>
        <Style TargetType="GridViewItem">
            <Setter Property="Margin" Value="0, 15, 15, 0"/>
        </Style>
    </GridView.ItemContainerStyle>
</GridView>

C#代码:

// My games list
public ObservableCollection<Game> OwnedGames { get; set; }

// Binding my games list to the GridView
BasicGridView.DataContext = OwnedGames;

现在我的下一步是添加过滤。 经过一番搜索,似乎解决方案是使用 CollectionViewSource。

这就是我最终得到的:

public ICollectionView OwnedGamesView { get; set; }

CollectionViewSource OwnedGamesViewSource = new CollectionViewSource();
OwnedGamesViewSource.Source = OwnedGames;
OwnedGamesView = OwnedGamesViewSource.View;

因为我现在要使用 CollectionView,所以我像这样更改了 GridView 的 Datacontext:

BasicGridView.DataContext = OwnedGamesView;

当 运行 应用程序时,一切仍然像这样工作,所以最后一步应该是自己执行过滤:

OwnedGamesView.Filter(...);

但是我的情况下不存在这种方法。 它未在 UWP 的 ICollectionView API 参考中列出: https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.data.icollectionview?view=winrt-20348

所以我想知道我如何仍然可以在 UWP 应用程序中完成这项工作? 或者有什么可能的选择?

我希望我的问题很清楚? 提前致谢! :)

使用 CollectionViewSource 的过滤不是针对生成的 View 集合,而是 CollectionViewSource 实例本身。向 CollectionViewSource.Filter 事件添加一个事件侦听器。请参阅示例 here

However this method doesn't exist in my case. It isn't listed on the ICollectionView API reference for UWP

ICollectionView不包含Filter,根据您的要求,您可以使用Microsoft.ToolkitAdvancedCollectionViewclass来处理。它包含 Filter 属性,您可以使用它来过滤集合并设置 SortDescriptions.

var acv = new AdvancedCollectionView(oc);

// Let's filter out the integers
int nul;
acv.Filter = x => !int.TryParse(((Person)x).Name, out nul);

// And sort ascending by the property "Name"
acv.SortDescriptions.Add(new SortDescription("Name", SortDirection.Ascending));

// AdvancedCollectionView can be bound to anything that uses collections. In this case there are two ListViews, one for the original and one for the filtered-sorted list.
RightList.ItemsSource = acv;