omarmallat
omarmallat

Reputation: 734

filtering observable collection

I'm new to wpf, Entity Framework 6 and LINQ. I'm having a data grid bounded to a CollectionViewSource, which is bounded to ObservableCollection. Simply I followed the tutorial found in https://msdn.microsoft.com/en-us/data/jj574514 and I succeed to add, update and delete from the data grid. the tutorial shows how to load a full table (i.e. category):

private void Window_Loaded(object sender, RoutedEventArgs e) 
{ 
     System.Windows.Data.CollectionViewSource categoryViewSource = 
     ((System.Windows.Data.CollectionViewSource)(this.FindResource("categoryViewSource"))); 

     _context.Categories.Load(); 
     categoryViewSource.Source = _context.Categories.Local; 
}

Now my question is very simple: What if I want to load some of the categories, and not all of them? I want some users to be able to update specific categories, so the grid will load only those categories.

Upvotes: 1

Views: 2688

Answers (2)

Cristian
Cristian

Reputation: 285

you need to use a filter.

categoryViewSource.View.Filter = item =>
                 {
                     Categories category = item as Categories; // hope this are your items
                     return category.Id > 10; // or put whatever condition you want
                 };

The above method would return only the categories that have Id > 10(just used Id as an example).

Also check this link: http://social.technet.microsoft.com/wiki/contents/articles/26673.aspx

Upvotes: 1

Insight
Insight

Reputation: 196

If you want to work with linq, you can try it this way:

ObservableCollection<Model> collection = new ObservableCollection<Model>();

ObservableCollection<Model> filteredCollection = new ObservableCollection<Model>(from item in collection where item.ID >0 && item.ID < 10 orderby item.ID select item);

You can bind an observablecollection directly to the ItemsSource property of a wpf datagrid, when i am not mistaken.

If you want to know more about linq, i suggest reading https://msdn.microsoft.com/de-de/library/bb397933.aspx

Upvotes: 1

Related Questions