Quick Tip: LINQ & Data Binding notifications - DevCorner

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:

image

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;
  };
image

 

Enjoy,

Alex

Published Tuesday, June 23, 2009 11:29 AM by Alex Golesh

Comments

# Links da Semana (22-26) – Novidades!

Calor? Frio? Ou tecnologia? Vamos então para mais uma listinha de links da semana: bestof’s, portfólios

Friday, June 26, 2009 11:46 AM by Gonçalo Chaves

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: