Wpf 将一个集合筛选为多个列表框

Wpf 将一个集合筛选为多个列表框,wpf,mvvm,filter,Wpf,Mvvm,Filter,我有一个视图模型: public class VM { public ObservableCollction<PersonRole> PersonRoles { get; private set; } } public class PersonRole { public int RoleID { get; set; } //.. } 公共类虚拟机 { 公共ObservableCollection PersonRoles{get;private set;}

我有一个
视图模型

public class VM
{
    public ObservableCollction<PersonRole> PersonRoles { get; private set; }
}

public class PersonRole
{
    public int RoleID { get; set; }
    //..
}
公共类虚拟机
{
公共ObservableCollection PersonRoles{get;private set;}
}
公共类角色
{
public int RoleID{get;set;}
//..
}
视图中
我必须显示三个
列表框

  • 所有具有
    RoleID==1
  • 具有
    RoleID==2的所有人员
  • 拥有
    RoleID==3的所有人员
怎么做比较好

  • 通过过滤在
    ViewModel
    中创建3个属性:

    Roles1=CollectionViewSource.GetDefaultView(PersonRoles)
    Roles1.Filter=o=>((PersonRole)o.RoleID==1

  • XAML
    中执行此操作的一些可能性?怎么做

  • 还有其他选择吗

根据您希望列表中的数据更改的频率,我可能会按照您的建议使用
ICollectionView
实例。但是,您将无法对3个单独的属性使用
CollectionViewSource.GetDefaultView
,因为它每次都会返回相同的对象实例。相反,您需要显式创建新的
ICollectionView
s:

this.Property1 = new ListCollectionView(this.PersonRoles);
this.Property2 = new ListCollectionView(this.PersonRoles);
this.Property3 = new ListCollectionView(this.PersonRoles);
// then set up filters
或者,如果列表中的数据很少更改,则最好在实际填充列表并实际存储3个集合时使用LINQ进行过滤:

this.Property1 = new ObservableCollection<PersonRole>(dataSource.Where(o => o.RoleID=1);
this.Property2 = new ObservableCollection<PersonRole>(dataSource.Where(o => o.RoleID=2);
//etc
this.Property1=新的ObservableCollection(dataSource.Where(o=>o.RoleID=1);
this.Property2=新的ObservableCollection(dataSource.Where(o=>o.RoleID=2);
//等
但是,如果您希望在整个列表中有规律地添加和删除项目,那么这种方法就不是特别好,因为这意味着您需要一直手动保持所有3个列表的同步


最后,您可以在XAML中设置集合视图,但如果没有某种形式的代码,您将无法对它们进行筛选。

我还建议您使用ICollectionView,但很好地解释了一些可选选项。