Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering ObservableCollection in WPF MVVM

I have a data-grid which is bind ObservableCollection. There is an Status field. I need to Filter by status when click on filter button. I use MVVM and need to filter inside the VM class.

<DataGrid
    CanUserResizeColumns="False" CanUserResizeRows="False" IsEnabled="{Binding IsKeySet}"
    Name="dgwTemplateDetails" CanUserAddRows="False" SelectionMode="Single"
    ItemsSource="{Binding OrderTemplateList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    AutoGenerateColumns="False" Width="auto" FontWeight="Normal" FontStyle="Normal">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Act Code" Width="75" Binding="{Binding ActCode}" IsReadOnly="True"/>
        <DataGridTextColumn Header="Act Name" Width="*" Binding="{Binding ActName}" IsReadOnly="True"/>
        <DataGridTextColumn Header="No. Of Days" Width="80" Binding="{Binding NoOfDays}"/>
        <DataGridTemplateColumn Header="To be Finish Date" Width="110" IsReadOnly="True">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding EarStartDt, StringFormat=dd/MM/yyyy, UpdateSourceTrigger=PropertyChanged}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <DatePicker SelectedDate="{Binding EarStartDt, StringFormat=dd/MM/yyyy, UpdateSourceTrigger=PropertyChanged}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Header="Act Status" Width="100" Binding="{Binding ActStatus}" IsReadOnly="True"/>
        <DataGridTextColumn Header="Remarks" Width="200" Binding="{Binding Remarks}" IsReadOnly="True"/>
    </DataGrid.Columns>
</DataGrid>
like image 505
Samudra Lakmal Avatar asked Dec 20 '22 07:12

Samudra Lakmal


1 Answers

I would use the ICollectionView for Filtering.

public ICollectionView MyView {get; private set;}

so in your ctor you can do:

 MyView = CollectionViewSource.GetDefaultView(OrderTemplateList);
 MyView.Filter = MyFilterAction;

so when your "button_ClickCommand" set an new Status in your Viewmodel you can simply call

MyView.Refresh();

and your filter will be re-evaluated

like image 109
blindmeis Avatar answered Dec 28 '22 07:12

blindmeis