I have a ViewModel:
public class VM
{
public ObservableCollction<PersonRole> PersonRoles { get; private set; }
}
public class PersonRole
{
public int RoleID { get; set; }
//..
}
In View I have to display three ListBoxes:
- all persons with
RoleID == 1 - all persons with
RoleID == 2 - all persons with
RoleID == 3
How it’s better to do?
-
Create 3 properties in
ViewModelwith filtering:Roles1 = CollectionViewSource.GetDefaultView(PersonRoles);
Roles1.Filter = o => ((PersonRole)o).RoleID == 1; -
Some possibilities to do this in
XAML? How? - More options?
Depending on how often you expect the data in the list to change, I would probably go with
ICollectionViewinstances as you suggest. You won’t be able to useCollectionViewSource.GetDefaultViewfor 3 separate properties, however, as it will return the same object instance every time. Instead, you’ll need to explicitly create newICollectionViews:Alternatively, if the data in the list is only going to change very rarely, it might be better to do the filtering using LINQ when you actually populate the list and actually store 3 collections:
This approach is not particularly good if you expect items to be added to and removed from the overall list with any regularity though, as it will mean that you need to manually keep all 3 lists syncronised all the time.
As a final comment, you can set up collection views in XAML but you will not be able to filter them without some form of code behind.