c# - 过滤 ObservableCollection 以仅显示某些项目

标签 c# wpf data-binding observablecollection icollectionview

我在这里点击了这个链接:http://jacobmsaylor.com/?p=1270

但我遇到了问题,正在尝试对其进行调整

<ListBox Name="PageList_ListBox" MouseDoubleClick="PageList_ListBox_OnMouseDoubleClick"
                             Background="#FFC9C9C9" Margin="0,5,0,0" ItemsSource="{Binding PageCollection, ElementName=This}">

.

public static ObservableCollection<MLBPage> _PageCollection = new ObservableCollection<MLBPage>();
public static ObservableCollection<MLBPage> PageCollection
        {
            get { return _PageCollection; }
        }

public ICollectionView _PageCollectionView { get; set; }

_PageCollectionView = CollectionViewSource.GetDefaultView(_PageCollection);

private bool FilterLeadersList(object item)
{
  MLBPage page = item as MLBPage;
  if (page.templateName.Contains("Leaders List"))
  {
    return true;
  }
  else
  {
    return false;
  }
}

我的 MLBPage 对象有 2 种类型......其中“templateName”可以是“Leaders List”或“Leader Headshots”......现在当我通过添加到按钮来过滤集合时:

_PageCollectionView.Filter = FilterLeadersList;

整个集合只是过滤(绑定(bind)到列表框的 _PageCollection 变为空白),而不是仅过滤名称中包含“Leaders List”的项目....

关于如何修改它以使其工作的任何帮助?

最佳答案

将您的代码更改为:

 private ObservableCollection<MLBPage> _PageCollection = new ObservableCollection<MLBPage>();            
 public ICollectionView _PageCollectionView { get; set; }

只需执行一次(例如在 ctor 中)

 //ctor
 _PageCollectionView = CollectionViewSource.GetDefaultView(_PageCollection);
 _PageCollectionView.Filter = FilterLeadersList,

使用 clear、add、remove 来改变你的 _PageCollection。

将列表框绑定(bind)到 View

<ListBox ItemsSource="{Binding _PageCollectionView}"/>

使用 Refresh 来刷新你的过滤器

 _PageCollectionView.Refresh();

关于c# - 过滤 ObservableCollection 以仅显示某些项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22541686/

相关文章:

c# - WPF 中的变量绑定(bind)

c# - AuthorizationCodeReceivedNotification 未将对象引用设置为对象的实例

C# 从 MemoryStream 打开 Office 文档和 Xps 文件

wpf - MVVM DataTemplate 绑定(bind)问题

wpf RowDetailsTemplate焦点

c# - 误解数据绑定(bind)基础知识和 DataContext——说来话长

c# - 在 System.Data.SqlCommand (C#) 中使用子查询 - 语法错误,在 SQL Server Mgmt Studio 中工作

c# - Xml 和数据集的问题

c# - DevExpress Windows 窗体的文件上传控件

wpf - MVVM:我应该将文本框直接绑定(bind)到模型还是应该先创建一个完整的属性?