Tuesday, January 21, 2014

Binding to a List - don't do it

In an earlier blog I described how to bind a datagrid to a Public Property List defined in the code behind. It turns out that if you deploy that solution it does not work. There's no error, the grid's ItemsSource has the correct number of rows, but no data shows in the DataGrid.

If you replace the List with an ObservableCollection (you will need to Import System.Collection.ObjectModel), the datagrid gets populated.

This must be because the ObservableCollection implements IPropertyChanged, an interface that allows bound controls to be made aware of changes to the collection. List does not implement this interface.

Why is the datagrid populated correctly in Visual Studio?

The List is being populated by a WCF call. I think in VS the call is quick and the collection is populated prior to the datagrid being bound to it. When I run the application on another computer via ClickOnce the WCF call takes longer so the List is not populated yet when the datagrid is bound.

Because IPropertyChanged is not implemented, subsequent changes to the List are not propagated to the datagrid.

No comments:

Post a Comment