Home > Silverlight > Two-Way binding Autogenerated columns in Silverlight DataGrid

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.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: