【发布时间】:2015-11-02 17:30:17
【问题描述】:
我应该为 DataGrid 添加过滤功能,该DataGrid 创建和绑定如下。
<DataGrid ItemsSource="{Binding Path=Things, Mode=TwoWay}" ...>
...
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Id}" />
...
</DataGrid.Columns>
</DataGrid>
根据MSDN article 我应该添加一个集合视图源并绑定到它。但是,在示例中,他们谈到了命名空间 local,我希望从数据上下文中获取我的东西。
<Window.Resources>
<local:Tasks x:Key="tasks" />
<CollectionViewSource x:Key="cvsTasks"
Source="{StaticResource tasks}"
Filter="CollectionViewSource_Filter" />
</Window.Resources>
有可能吗?当我尝试过时,我得到了一堆空单元格。单击它们用于打开一个对话框,其中单击的行的值是可编辑的(并预先填充了表中的数据),但现在我到处都是空框。我的版本是这样的。
<Window.Resources>
<CollectionViewSource x:Key="ThingsFiltered"
Source="{Binding Path=Things}"
Filter="ThingsFiltered_OnFilter" />
</Window.Resources>
数据网格中的绑定现在是这样完成的。
<DataGrid ItemsSource="{Binding Source=ThingsFiltered}" ...>
...
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Id}" />
...
</DataGrid.Columns>
</DataGrid>
我的猜测是我没有正确绑定集合视图源。事实上,应该处理过滤器的方法根本没有被调用。在数据网格及其列中尝试了不同的语法之后,我承认我不知道如何使它工作。有什么建议吗?
【问题讨论】:
-
你在哪里定义了“事物”?
-
@MaximeTremblay-Savard 在我的视图模型中。 Things 字段是其中的一部分,可在数据上下文中使用(直接绑定时)。它的类型是 ObservableCollection
。 -
如果没有过滤器,您是否能够使用您的 Things 填充数据网格?
-
另外,您能否发布您的 ThingsFiltered_OnFilter 实现
-
@MaximeTremblay-Savard 是的,在我添加集合视图源(直接绑定到在构造函数中设置为数据上下文的视图模型)之前,它可以完美运行。我在过滤器的处理程序中 throw new NotImplementedException() 但它没有到达那里。这就是为什么我要问是否可以过滤来自视图模型的东西,或者它们显示的过滤是否只能在本地资源或其他东西上完成。
标签: c# wpf xaml data-binding filter