【问题标题】:C# Filter ListView without setting the ItemSource newC#过滤ListView而不设置ItemSource新
【发布时间】:2016-12-19 11:05:32
【问题描述】:

我想知道是否可以在 C# 中过滤 ListView 而无需设置不同的 ItemSource

现在我在每次条件变化时设置一个新的ItemsSource

ListView.ItemsSource = list.Where(item => {<<condition>>});

我的问题:在此列表中,我有包含图片的用户配置文件。每次我设置一个新的 ItemSource 时,图片都会重新加载。是否可以在android中使用过滤器之类的东西来“隐藏”不满足上述条件的行?

【问题讨论】:

标签: c# listview filter


【解决方案1】:

您可以通过在设置为 ItemsSource 的 ObservableCollection 中添加或删除项目来避免实际更改 ItemsSource。列表控件将获取与这些插入和删除相关的 ObservableCollection 事件,并酌情更新。

例如以下函数应根据过滤器表达式从完整列表中填充过滤列表。如果过滤后的列表绑定到列表控件,那么只需调用此函数即可获得所需的效果。

static void FilterList<T>(List<T> masterList, ObservableCollection<T> filteredList, Func<T, bool> filterExpression)
{
    foreach (var item in masterList)
    {
        if (filterExpression(item))
        {
            if (!filteredList.Contains(item))
            {
                filteredList.Add(item);
            }
        }
        else
        {
            if (filteredList.Contains(item))
            {
                filteredList.Remove(item);
            }
        }
    }
}

例如

FilterList(allCars, filteredCars, (user) => user.Age >= 50);

请注意,此函数可能需要额外的逻辑来保留顺序,而不是总是在末尾添加新的过滤项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-25
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    相关资源
    最近更新 更多