我模仿了 Josh Smith 的设计 http://msdn.microsoft.com/en-us/magazine/dd419663.aspx并想添加过滤。
在 AllCustomersViewModel 中,他创建了 CustomerViewModel 的 ObservableCollection,该集合通过 AllCustomers 属性链接到 xaml
public ObservableCollection<CustomerViewModel> AllCustomers { get; private set; }
在 xaml 中,AllCustomers 设置为 CollectionViewSource。
说到这里,我想就如何扩展此功能以包括过滤提供建议。我不担心 xaml 方面的事情,更多的是在 ViewModel 中实现它。
最佳答案
实际上,您根本不需要在 XAML 中定义 CollectionViewSource
。这一切都可以在您的 ViewModel 中完成。
在 XAML 中直接将集合绑定(bind)到 ListBox:
<ListBox ItemsSource="{Binding AllCustomers}"/>
在 ViewModel 中,您可以通过获取与您的集合相关的默认 CollectionView 来应用过滤器,如下所示:
ICollectionView defaultCollectionView = CollectionViewSource
.GetDefaultView(AllCustomers);
defaultCollectionView.Filter = p => ((CustomerViewModel)p).IsCompany;
假设IsCompany
是一个 bool 属性。过滤器采用谓词(您可以将其替换为任何返回 bool 的委托(delegate))。
顺便说一句,您还可以从 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;
}
}
关于c# - 如何向 Josh Smith 的 MVVM msdn 设计添加过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21358767/