问题
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