绑定集合的子集

dot*_*hen 3 c# data-binding wpf

我有一个ObservableCollection<Person>对象.所述Person对象具有NameType属性,其中,Type或者是studentteacher.有没有办法将a绑定ComboBoxObservableCollection<Person>对象的子集,Type只有属性teacher

Roh*_*ats 8

ICollectionView 这是你的答案 -

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

您可以使用此属性绑定comboBox ItemSource.从源集合中添加或删除任何项目时,将自动过滤此集合.