Reputation: 7
I am trying to bind my collection to a listbox. The collection contains some items which are to be hidden and are to be shown based on certain conditions.But when I do this the alternate styles are not applied properly.
For example: Case 1 : where all items are visible, I get the output like this: Item1(grey) Item2(white) Item3(grey) Item4(white) Item5(grey) Item6(white) Item7(grey)
Case2: where Item2 is hidden, I get the output as: Item1(grey) Item3(grey) Item4(white) Item5(grey) Item6(white) Item7(grey)
How do I resolve this without rebinding the collection?
Upvotes: 0
Views: 158
Reputation: 14332
Rather than hide the items (presumably in the ListBoxItem
control template, or the ListBox
ItemTemplate
), you should use a CollectionViewSource
to filter them out.
This is because the items are still technically there - you cannot see them but the listbox can.
See this link for details on filtering. http://wpftutorial.net/DataViews.html
To filter a collection view you can define a callback method that determines if the item should be part of the view or not. That method should have the following signature: bool Filter(object item). Now set the delegate of that method to the Filter property of the CollectionView and you're done.
ICollectionView _customerView = CollectionViewSource.GetDefaultView(customers);
_customerView.Filter = CustomerFilter
private bool CustomerFilter(object item)
{
Customer customer = item as Customer;
return customer.Name.Contains( _filterString );
}
Upvotes: 0