Archive

Archive for January, 2011

Two-Way binding Autogenerated columns in Silverlight DataGrid

A colleague ask me why his property didn’t update while he was clicking on a checkbox in a column of a DataGrid.
He has set the ItemsSource of his DataGrid to an ObservableCollection of objects with the INotifyPropertyChanged inferface implemented and the setters fires the PropertyChanged event.
The problem is the default value of the ‘binding mode’ of a column (also any binding in Silverlight) is ‘OneWay’, this will means that the property is read only.
You can’t specify the ‘binding mode’ in XAML because there is no XAML for the bindings of the colums with autogenerated columns.

For this problem there is an easy workaround: add the ‘AutoGeneratingColumn’ event to your DataGrid and add the following code in the code behind file:

 private void dataGrid1_AutoGeneratingColumn(object sender, 
_DataGridAutoGeneratingColumnEventArgs e)
        {
           if(e.Column.GetType() == typeof(DataGridCheckBoxColumn))
           {
               DataGridCheckBoxColumn dgc = (DataGridCheckBoxColumn)e.Column;
               dgc.Binding.Mode = BindingMode.TwoWay;
           }
        }

You can do the same for a DataGridTextColumn by changing the if structure:

 if(e.Column.GetType() == typeof(DataGridTextColumn))
           {
               DataGridTextColumn dgc = (DataGridTextColumn)e.Column;
               dgc.Binding.Mode = BindingMode.TwoWay;
           }

You can download my demo code on this link.