Monday, April 27, 2015

WPF: How to apply more than one filter to view of a collection

Let's assume FirstName and LastName are two members of your class "Model". Your View Model is an observable collection with "MyCollection" property that are bound to a data grid called myDataGrid. This little snippet shows how to filter data in the grid by rolling your separate conditions into a single predicate.

public class Model
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }


    public class MyViewModel : ObservableCollection<Model>
    {
        public ICollectionView MyCollection { get; private set; }
        public MyViewModel()
        {
            try
            {
                List<Model> model = new List<Model>();

                model.Add(new Model { FirstName = "John", LastName = "Doe" });
                model.Add(new Model { FirstName = "Jane", LastName = "Doe" });
                MyCollection = CollectionViewSource.GetDefaultView(model);
            }
            catch (Exception e)
            {
                string errorMessage = "Message: " + e.Message;
                MessageBox.Show(errorMessage, "Application Error - " + e.Source);
            }
        }
    }

 
private void Search_OnClick(object sender, RoutedEventArgs e)

{
 MyViewModel myViewModel = new MyViewModel();

// Collection which will take your Filter

var _itemSourceList = myViewModel.MyCollection;


var filter = new Predicate<object>(item => ((Model)item).FirstName.ToString().Contains("John") && ((Model)item).LastName.ToString().Contains("Doe"));

_itemSourceList.Filter = filter;

 myDataGrid.ItemsSource = myViewModel.MyCollection;
}


<StackPanel>
<Button Width="Auto" VerticalAlignment="Top" HorizontalAlignment="Left" Content="Search" Click="Search_OnClick" Margin="10"/>

<DataGrid x:Name="tsxCompareDataGrid"

HorizontalAlignment="Left"

VerticalAlignment="Top"

SelectionMode="Extended"

SelectionUnit="Cell" />

</StackPanel>