【问题标题】:Can you filter an ICollectionView in an UWP app?你可以在 UWP 应用程序中过滤 ICollectionView 吗?
【发布时间】:2021-11-20 00:09:12
【问题描述】:

我仍在通过开发小型 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 应用程序中进行这项工作? 或者有什么可能的替代方案?

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

【问题讨论】:

    标签: c# xaml filter gridview uwp


    【解决方案1】:

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

    【讨论】:

    • 感谢您花时间回答。但是,正如您在下面的链接中看到的那样,Filter 事件甚至不存在。我还想知道这个过滤器事件是从哪里/何时触发的? docs.microsoft.com/en-us/uwp/api/…
    • 我明白了。在这种情况下,您最好直接绑定到ObservableCollection 并使用要过滤的原始列表的内存缓存自己执行过滤。这可以使用简单的Where LINQ 查询来完成。
    • 这是一个很好的解决方案,但是我使用了 AdvancedCollectionView。但是,您的解决方案是我考虑过的,并且会更好地与旧 Windows 版本兼容。
    【解决方案2】:

    但是在我的情况下这种方法不存在。它未列在 UWP 的 ICollectionView API 参考中

    ICollectionView 不包含Filter,根据您的要求,您可以使用Microsoft.Toolkit AdvancedCollectionView 类来处理。它包含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;
    

    【讨论】:

    • 谢谢,这解决了我的问题并且很容易实现! :)
    猜你喜欢
    • 2014-02-24
    • 2016-10-26
    • 1970-01-01
    • 2022-01-20
    • 2011-01-09
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 2018-10-22
    相关资源
    最近更新 更多