You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UWP应用中能否对ICollectionView进行过滤?无Filter方法如何解决?

UWP中ICollectionView无Filter方法的过滤实现方案

UWP平台的ICollectionView接口确实未提供WPF中存在的Filter属性,这是平台实现差异导致的,以下是3种可行的替代实现方案:

方案1:使用CollectionViewSource的Filter事件(无额外依赖,原生实现)

直接操作你已经创建的CollectionViewSource实例,挂载其自带的Filter事件实现过滤逻辑,需要刷新过滤结果时调用View的Refresh方法即可。

// 你已有的初始化代码
CollectionViewSource OwnedGamesViewSource = new CollectionViewSource();
OwnedGamesViewSource.Source = OwnedGames;
OwnedGamesView = OwnedGamesViewSource.View;
// 绑定到GridView
BasicGridView.DataContext = OwnedGamesView;

// 注册Filter事件
OwnedGamesViewSource.Filter += (s, e) =>
{
    if (e.Item is Game game)
    {
        // 示例过滤逻辑:只显示名称包含搜索关键词的游戏
        e.Accepted = game.Name.Contains(SearchKeyword, StringComparison.OrdinalIgnoreCase);
    }
    else
    {
        e.Accepted = false;
    }
};

// 过滤条件变化时,调用此方法刷新结果
void RefreshFilter()
{
    OwnedGamesView.Refresh();
}

方案2:维护双集合手动过滤(逻辑最直观,适合简单场景)

保留原始全量游戏集合OwnedGames,额外创建一个用于UI绑定的过滤集合,过滤条件变化时直接更新这个绑定集合的内容。

// 原始全量游戏集合
public ObservableCollection<Game> OwnedGames { get; set; }
// 用于绑定到GridView的过滤后集合
public ObservableCollection<Game> FilteredGames { get; set; } = new();

// 过滤逻辑实现
void UpdateFilter(string keyword)
{
    FilteredGames.Clear();
    var filtered = OwnedGames.Where(g => g.Name.Contains(keyword, StringComparison.OrdinalIgnoreCase));
    foreach (var game in filtered)
    {
        FilteredGames.Add(game);
    }
}

// XAML绑定改为绑定FilteredGames即可
BasicGridView.DataContext = FilteredGames;

方案3:使用社区工具包AdvancedCollectionView(支持复杂过滤、排序、分组)

如果需要频繁操作过滤、排序逻辑,可以使用Windows Community Toolkit提供的AdvancedCollectionView组件,它直接支持Filter属性设置,用法和WPF的过滤逻辑高度一致。

// 初始化AdvancedCollectionView
var acv = new AdvancedCollectionView(OwnedGames, true);
// 设置过滤逻辑
acv.Filter = o => o is Game game && game.Name.Contains(SearchKeyword, StringComparison.OrdinalIgnoreCase);
// 绑定到GridView
BasicGridView.DataContext = acv;

// 过滤条件变化时调用Refresh即可
acv.Refresh();

内容的提问来源于stack exchange,提问作者nwarrenfl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 07:24:03