dotancohen
dotancohen

Reputation: 31471

Bind subset of collection

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?

Upvotes: 3

Views: 3290

Answers (3)

Rohit Vats
Rohit Vats

Reputation: 81233

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..

Upvotes: 8

ahmet
ahmet

Reputation: 646

You can do this programatically as follows:

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

Upvotes: 1

Klaus78
Klaus78

Reputation: 11896

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

Upvotes: 2

Related Questions