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 .

+4
source share
2 answers

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:

http://bea.stollnitz.com/blog/?p=31

http://bea.stollnitz.com/blog/?p=392

+9
source

An easier way is to use Visibility in XAML.

Suppose your ListBox ItemTemplate uses a StackPanel to store your data, in which case you have 2 TextBlock inside this StackPanel (1 for Data1, 1 for Data2).

So you have to bind this StackPanel Visibility to IsActive

-1
source

All Articles