Reputation: 2616
I have mimicked Josh Smith's design from http://msdn.microsoft.com/en-us/magazine/dd419663.aspx and would like to add filtering.
In the AllCustomersViewModel he creates an ObservableCollection of CustomerViewModel, which is linked to the xaml via the property AllCustomers
public ObservableCollection<CustomerViewModel> AllCustomers { get; private set; }
In the xaml AllCustomers is set as a CollectionViewSource.
In saying this, I would like advise on how to extend this functionality to include filtering. I am not to worried about the xaml side of things, more implementing it in the ViewModel.
Upvotes: 2
Views: 276
Reputation: 81253
Actually you don't need CollectionViewSource
at all to be defined in XAML. It can be done all in your ViewModel.
Directly bind collection to ListBox in your XAML:
<ListBox ItemsSource="{Binding AllCustomers}"/>
and in ViewModel you can apply filter by getting default CollectionView related to your collection like this:
ICollectionView defaultCollectionView = CollectionViewSource
.GetDefaultView(AllCustomers);
defaultCollectionView.Filter = p => ((CustomerViewModel)p).IsCompany;
Assuming IsCompany
is a bool property. Filter takes predicate (you can replace it with any delegate returning bool).
On a side note you can also apply sorting and grouping from ViewModel itself.
If you want to have CollectionViewSource
in XAML, you can apply filter in code-behind.
<CollectionViewSource x:Key="MyCVS"
Source="{Binding AllCustomers}"
Filter="MyCVS_Filter"/>
and in code behind:
void MyCVS_Filter(object sender, FilterEventArgs e)
{
CustomerViewModel item = e.Item as CustomerViewModel;
if (item.IsCompany)
{
e.Accepted = true;
}
else
{
e.Accepted = false;
}
}
Upvotes: 2