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的所有人员
- 通过过滤在
中创建3个属性:ViewModel
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,但很好地解释了一些可选选项。