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.
My code simplified looks following:
public class MainViewModel : ViewModelBase , IBarcodeHandler
{
public ObservableCollection<TraceDataItem> TraceItemCollectionViewSource { get; set; }
}
My 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>
How I can add ICollectionView
here in order to apply filtering to the view?
You may invoke the Filter callback from a Command and expose the View property from CollectionViewSource :
A
CollectionView
is not always the best solution. you can also filter your collection using some simple LinQ. Take this simple example:The beauty of this method is that you can add some complex filtering requirements. One thing to note: whenever any properties in this method are changed, you'd need to call
NotifyPropertyChanged("FilteredData")
to ensure that the UI will be updated accordingly.You would need to:
then, somewhere in the code (maybe in the constructor) add your filter:
And, in XAML, you would need to change the binding to TraceItemCollectionView property.