I'm working with silverlight and I want to filer an ObservableCollection.
So I started to look att ICollectionView, because there is no CollectionViewSource in Silverlight and it contains an absure amount of methods and events. I've searched for a while and I wonder if anyone has example code of an implementation of ICollectionView?
CollectionViewSource is now available in Silverlight 3. Check out a good article about this here.
Unfortunately ICollectionView is only used for the DataGrid in Silverlight 2.0, and its only implementation is ListCollectionView, which is internal to System.Windows.Controls.Data.
If you are not binding to a DataGrid, ICollectionView will not give you much because it is not used by the basic controls (such as listbox) as far as I can tell, since it is defined in the Data controls assembly and not in the core.
This is a pretty big difference with WPF.
But to the point of your question, the assembly containing the DataGrid does have an implementation that might help you if you want to learn how it is done. Worst case, reflector is your friend...
One method would be to use a Value Converter if you want to do data binding to the ObservableCollection.
Another method would be to use LINQ in a ViewModel CLR object that would do the filtering based on properties in the ViewModel like this (see the implementation method UpdateFilteredStores() at the bottom):
namespace UnitTests
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
public class ViewModel : INotifyPropertyChanged
{
private string name;
public ViewModel()
{
this.Stores = new ObservableCollection<string>();
this.Stores.CollectionChanged += new NotifyCollectionChangedEventHandler(this.Stores_CollectionChanged);
// TODO: Add code to retreive the stores collection
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
public ObservableCollection<string> Stores { get; private set; }
public IEnumerable<string> FilteredStores { get; private set; }
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
this.UpdateFilteredStores();
}
}
private void Stores_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
this.UpdateFilteredStores();
}
private void UpdateFilteredStores()
{
this.FilteredStores = from store in this.Stores
where store.Contains(this.Name)
select store;
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("FilteredStores"));
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With