Filtering ObserverableCollection to display only certain items

我只是一个虾纸丫 提交于 2019-12-11 01:04:08

问题


I was following this link here: http://jacobmsaylor.com/?p=1270

but i'm having problems with it, trying to make tweaks to it

<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;
  }
}

My MLBPage object has 2 types... where the "templateName" can be either "Leaders List" or "Leader Headshots".. now when I filter the collection by adding to a button:

_PageCollectionView.Filter = FilterLeadersList;

the whole collection just filters (the _PageCollection binded to a listbox turns blank) instead of only the items that contain "Leaders List" within the name....

any help on how i can modify this to work?


回答1:


change your code into:

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

just do this once (eg. within ctor)

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

use clear, add , remove to alter your _PageCollection.

bind your listbox to your view

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

use Refresh to refresh your filter

 _PageCollectionView.Refresh();


来源:https://stackoverflow.com/questions/22541686/filtering-observerablecollection-to-display-only-certain-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!