如何通过MVVM为DataGrid ItemSource设置过滤器 [英] How to set a filter for a DataGrid ItemSource via MVVM

查看:221
本文介绍了如何通过MVVM为DataGrid ItemSource设置过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 DataGrid 绑定到XAML中的CollectionViewSource 。

I have a DataGrid bound to a CollectionViewSource in XAML.

<Window.Resources>
  <local:MainWindowViewModel x:Key="ViewModel"/>
  <CollectionViewSource x:Key="cvsEntries" 
                        Source="{Binding LogEntriesStore, 
                                 Source={StaticResource ViewModel}}"/>
</Window.Resources>

LogEntriesStore 是一个 ObservableCollection 是一个DTO,在本次讨论中并不重要)

LogEntriesStore is an ObservableCollection (LogEntry is a DTO that's not important in this discussion)

将DataGrid 声明为:

The DataGrid is declared as:

<DataGrid AutoGenerateColumns="False" 
          Margin="0" 
          Name="dataGrid1" 
          ItemsSource="{Binding Source={StaticResource cvsEntries}}" 
          IsReadOnly="True">

现在我在这个 DataGrid 中的各种单元格上有上下文菜单,关闭过滤请求。右键单击一个单元格,然后选择过滤器以过滤所有行,并显示此特定值。

Now I have context menus on various cells in this DataGrid, to kick off a request for filtering. Right click on a cell, and pick filter to filter all the rows, and show only this particular value.

MVVM获取过滤请求,但现在是棘手的位。如何在CollectionViewSource上设置过滤器?

The MVVM gets the request to filter, but the now the tricky bit. How do I set the filter on the CollectionViewSource?

(除此之外 - 这将是一个在公园里散步的Silverlight PagedCollectionView 但是在WPF中似乎不可用,是吗?)

(as an aside -- this would have been a walk in the park with a Silverlight PagedCollectionView but that doesn't seem to be available in WPF, is that right?)

推荐答案

简单。您只需在视图模型中移动集合视图:

Very simple. You just need to move the collection view inside the view model:


  1. MainWindowViewModel 定义一个类型为 ICollectionView 的属性:

  1. In MainWindowViewModel define a property of type ICollectionView:

public ICollectionView LogEntriesStoreView { get; private set; }


  • 刚刚初始化了 LogEntriesStore 属性,您需要使用以下代码初始化 LogEntriesStoreView 属性:

  • Right after you have initialized the LogEntriesStore property, you need to initialize the LogEntriesStoreView property with the following code:

    LogEntriesStoreView = CollectionViewSource.GetDefaultView(LogEntriesStore);
    


  • 然后,您需要删除 CollectionViewSource 从XAML修改 ItemsSource 绑定到指向新创建的集合视图属性:

  • Then you need to remove the CollectionViewSource from XAML and modify the ItemsSource binding to point to the newly created collection view property:

    <DataGrid AutoGenerateColumns="False" 
              Margin="0" 
              Name="dataGrid1" 
              ItemsSource="{Binding LogEntriesStoreView, Source={StaticResource ViewModel}}" 
              IsReadOnly="True">
    


  • 就是这样。现在,您可以访问视图模型中的集合视图,您可以在其中修改过滤器。

    That's it. Now you have the access to the collection view inside your view model, where you can modify the filter.

    这篇关于如何通过MVVM为DataGrid ItemSource设置过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆