I have a collection of objects that look like this:
List<MyObject> objects = new List<MyObject>();
objects.Add(new MyObject("Stapler", "Office"));
objects.Add(new MyObject("Pen", "Office"));
objects.Add(new MyObject("Mouse", "Computer"));
objects.Add(new MyObject("Keyboard", "Computer"));
objects.Add(new MyObject("CPU", "Computer"));
class MyObject{
public string name;
public string category;
public MyObject(string n, string c){
name=n;
category=c;
}
}
Can I bind that collection to a List in WPF, and have it display the categories of the objects (without duplicates)? (maybe along with the count of objects that’s in that category)
For example, i would like the list to show only two items, “Office” and “Computer”
Use a
CollectionViewSourcewith aPropertyGroupDescription.In your
Resources, add the following:Then, for your
ItemsControl, set theItemsSourceto{Binding Source={StaticResource MyCollectionViewSource}}.To style the header template, set the
ItemsControl.GroupStyleproperty. Also create aDataTemplatefor the items.Read an excellent blog post from Bea Stollnitz here.