我从http://msdn.microsoft.com/en-us/magazine/dd419663.aspx模仿Josh Smith的设计,并希望添加过滤功能。
在AllCustomersViewModel中,他创建了一个CustomerViewModel的ObservableCollection,它通过属性AllCustomers链接到xaml
public ObservableCollection<CustomerViewModel> AllCustomers { get; private set; }
在xaml中,AllCustomers设置为CollectionViewSource。
在说这个时,我想建议如何扩展此功能以包括过滤。我不担心xaml方面的问题,更多的是在ViewModel中实现它。
答案 0 :(得分:2)
实际上,您根本不需要在XAML中定义CollectionViewSource
。它可以在ViewModel中完成。
直接将集合绑定到XAML中的ListBox:
<ListBox ItemsSource="{Binding AllCustomers}"/>
在ViewModel中,您可以通过获取与您的收藏相关的默认CollectionView 来应用 过滤器,如下所示:
ICollectionView defaultCollectionView = CollectionViewSource
.GetDefaultView(AllCustomers);
defaultCollectionView.Filter = p => ((CustomerViewModel)p).IsCompany;
假设IsCompany
是bool属性。过滤器使用谓词(您可以将其替换为任何返回bool的委托)。
另外,您还可以从ViewModel本身应用排序和分组。
如果您希望在XAML中使用CollectionViewSource
,则可以在代码隐藏中应用过滤器。
<CollectionViewSource x:Key="MyCVS"
Source="{Binding AllCustomers}"
Filter="MyCVS_Filter"/>
并在代码背后:
void MyCVS_Filter(object sender, FilterEventArgs e)
{
CustomerViewModel item = e.Item as CustomerViewModel;
if (item.IsCompany)
{
e.Accepted = true;
}
else
{
e.Accepted = false;
}
}