filtering observable collection

entity-framework-6 linq observablecollection wpf

Question

Entity Framework 6 and LINQ are all new to me. I have a data grid that is tied to an ObservableCollection through a CollectionViewSource. Simply by according to the instructions in https://msdn.microsoft.com/en-us/data/jj574514, I was able to add to, alter, and delete data from the grid. The tutorial demonstrates how to load a complete table, or 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, let me ask you a pretty straightforward question: What if I only want to load certain of the categories? The grid will only load those categories since I want some users to be able to update particular categories.

1
0
4/30/2015 7:57:56 AM

Accepted Answer

You must apply 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 aforementioned approach would only return categories with Ids greater than 10. (just used Id as an example).

Check out this link as well: http://social.technet.microsoft.com/wiki/contents/articles/26673.aspx

0
4/30/2015 9:01:39 AM

Popular Answer

You can try using linq in the following manner if you want to:

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);

If I'm not mistaken, you may directly tie an observablecollection to a wpf datagrid's ItemsSource property.

I recommend reading https://msdn.microsoft.com/de-de/library/bb397933.aspx if you want to learn more about linq.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow