3

I have an ObservableCollection<Person> object. The Person objects have Name and Type properties, where Type is either student or teacher. Is there any way to bind a ComboBox to a subset of the ObservableCollection<Person> object, where the Type property is only teacher?

H.B.
  • 166,899
  • 29
  • 327
  • 400
dotancohen
  • 30,064
  • 36
  • 138
  • 197

3 Answers3

8

ICollectionView is your answer here -

public ICollectionView Teachers
{
   get
   {
      // Persons is your ObservableCollection<Person>.
      var teachers = CollectionViewSource.GetDefaultView(Persons);
      teachers.Filter = p => (p as Person).Type == "Teacher";
      return teachers;
   }
}

You can bind your comboBox ItemSource with this property. When any item is added or removed from your source collection, this collection will be filtered automatically..

Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
2

This will help you

WPF Binding to a Combo using only a subset of a Collection's items

Here are mentioned concepts like CollectionViewSource, Filters ecc...

Have a look also at

Data bind to a portion of a collection

Community
  • 1
  • 1
Klaus78
  • 11,648
  • 5
  • 32
  • 28
1

You can do this programatically as follows:

MyComboBox.ItemsSource = a.Where((obj, r) => { return (obj.Type == "student"); }).ToList();
ahmet
  • 646
  • 6
  • 14