使用ICollectionView过滤ObservableCollection [英] Filtering ObservableCollection with ICollectionView
问题描述
我将 ObservableCollection
绑定到 dataGrid
,现在我想过滤显示的数据,我看到我需要使用 ICollectionView
,但是我不确定如何在 MVVM $ c中添加
ICollectionView
$ c>模式。
I have ObservableCollection
binded to dataGrid
and now I want to filter the presented data I see that I need to use ICollectionView
but I am not sure how to add ICollectionView
with my MVVM
pattern.
我的简化代码如下:
public class MainViewModel : ViewModelBase , IBarcodeHandler
{
public ObservableCollection<TraceDataItem> TraceItemCollectionViewSource { get; set; }
}
我的XAML
<Window xmlns:controls="clr-namespace:Mentor.Valor.vManage.RepairStation.Controls"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
<DataGrid Grid.Row="2" ColumnWidth="*" ItemsSource="{Binding TraceItemCollectionViewSource , Mode=TwoWay , UpdateSourceTrigger=PropertyChanged}" RowStyle="{StaticResource TraceRowStyle}" IsReadOnly="True" Name="TraceDataGrid" Margin="5,5,5,5" Padding="5,5,5,5" AutoGenerateColumns="False">
</Window>
如何在此处按顺序添加 ICollectionView
要对视图应用过滤?
How I can add ICollectionView
here in order to apply filtering to the view?
推荐答案
您将需要:
public class MainViewModel : ViewModelBase, IBarcodeHandler
{
public ICollectionView TraceItemCollectionView
{
get { return CollectionViewSource.GetDefaultView(TraceItemCollectionViewSource); }
}
public ObservableCollection<TraceDataItem> TraceItemCollectionViewSource { get; set; }
}
然后,在代码中的某个地方(可能在构造函数中)添加过滤器:
then, somewhere in the code (maybe in the constructor) add your filter:
TraceItemCollectionView.Filter = o =>
{
var item = (TraceDataItem) o;
//based on item, return true if it should be visible, or false if not
return true;
};
而且,在XAML中,您需要更改对TraceItemCollectionView属性的绑定。
And, in XAML, you would need to change the binding to TraceItemCollectionView property.
这篇关于使用ICollectionView过滤ObservableCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!