Click here to Skip to main content
16,012,352 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've created a WPF custom ComboBox which has the ability to filter items according to a "search string". The ComboBox ItemsSource is bound to a ObservableCollection.

The ObservableCollection is a collection of "Person" object. It exposes a property "Usage Count".

Now if the "search string" is empty i have to show the Top 30 records from the ObservableCollection. The "UsageCount" property in the "Person" class decides the Top 30 Records(i.e. the the Top 30 records with the maximum UsageCount has to be displayed). The UsageCount property changes dynamically. How do i achieve this.. Please help. Thanks in advance :)
Posted

As you have rightly identified, the ObservableCollection is not quite the right tool for the job here, so what do you do? Well, fortunately for us, WPF provides something called the CollectionView which you can think of as a wrapper around a collection. In order to use it, expose the item that you want to bind on as an ICollectionView item like this:
C#
public ICollectionView MyView { get; private set; }
Now, you fill it like this:
C#
IList<Person> people = GetPeople();
MyView = CollectionViewSource.GetDefaultView(people);
Finally, you just need to filter the data (using whatever algorithm you need to filter this list on) and then update the ICollectionView using
C#
MyView.Refresh();
 
Share this answer
 
Comments
VJ Reddy 1-May-12 8:09am    
Good point. 5!
I have not tested but I think the following may be helpful.

1. Implement INotifyPropertyChanged interface and in the setter of UsageCount property, call the PropertyChanged event handler method.
2. In the PropertyChanged event handler method set the DataContext using LINQ query as explained here http://msdn.microsoft.com/en-us/library/bb910060.aspx[^]
3. The following LINQ query can be used.
C#
this.DataContext = Persons.OrderBy (p => p.UsageCount, new descendingOrderComparer()).Take(30);

//Assuming that the UsageCount is of type int.
//For descending order comparison, Comparer is required.
public class descendingOrderComparer  : IComparer<int> {
	public int Compare(int first, int second)  {
		return second - first;
	}
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900