Silverlight ListBox with ObservableCollection <T> and Dynamic Filter
Suppose I have this class:
public class MyData { public bool IsActive{get;set;} public String Data1 {get;set;} public String Data2 {get;set;} } and
ObservableCollection<MyData> data = new ObservableCollection<MyData>; ListBox.ItemsSource = data; Adding items to ObservableCollectionworks as expected; however, I want to make sure that only objects with IsActive set to "true" are displayed in my list - I cannot use the Linq query to set the ItemsSource, because then it is not ObservableCollection, its IEnumerable and does not make any notification about updates in the list .
Your answer is CollectionViewSource. Instead of binding to a list, bind an instance of CollectionViewSource.
The following is a slightly degenerate example (I'm not sure if you use ViewModels, Locators, etc. to resolve your data and your list.)
Suppose in your markup you have a CollectionViewSource declared in your resources as follows:
<phone:PhoneApplicationPage.Resources> <CollectionViewSource x:Key="src"/> </phone:PhoneApplicationPage.Resources> Then the list binding looks like this:
<ListBox x:Name="MyListBox" ItemsSource="{Binding Source={StaticResource src}}"> Finally, in the code, you can marry your list and your source for viewing the collection:
var collectionView = this.Resources["src"] as CollectionViewSource; // Check for null, etc. collectionView.Source = observableCollectionThatIAmBindingTo; collectionView.View.Filter=new Predicate<Object>(o => ((ItemType)o).IsActive ); You can also read Bea Stollnitz related articles: