Quick Tip: LINQ & Data Binding notifications
In Silverlight & WPF we could databind to the LINQ query results:
private ObservableCollection<string> someData = new ObservableCollection<string>();
//Somewhere in code
someData.Add("Alex");
someData.Add("Alen");
someData.Add("Josh");
someData.Add("Brad");
var res = from data in someData
where data.StartsWith("A")
select data;
listbox.ItemsSource = res;
”listbox” is the name of the Listbox on my XAML page.
When application will load we will get expected results:
But what happens when out collection (reminder: ObservableCollection, which implements INotifyCollectionChanged) changed?
someData.Add("Antony");
Nothing! Because we bounded to the LINQ query (predicate), and the query was executed while databinding occurred :) LINQ query does not fires any notifications because it is not re-evaluated on collection change, but on usage of the predicate.
Now the quick workaround:
Rebind once again to the same predicate (on collection change event), and it have you UI updated:
someData.CollectionChanged += (s, e) =>
{
listbox.ItemsSource = null;
listbox.ItemsSource = res;
};
Enjoy,
Alex