views:

284

answers:

2

My List<BusinessObject> has some public properties that I want to bind to columns in a DataGrid. Unfortunately, the names of the public properties are not good and I may not even know what they are until runtime. For this reason, I set AutoGenerateColumns=True and interecept each DataGridAutoGeneratingColumnEvent so I can inspect what it is and either cancel it, hide it, or name the header something else.

It works great but I cannot figure out how to set the Mode=TwoWay so that my INotifyPropertyChanged events get fired once all the columns are generated and somebody edits a cell.

Bonus question: On navigating up and down the rows of the grid, does the grid's datacontext automatically get set with that row's BusinessObject?

A: 

Thanks to this post, I learned that the binding happens on DataGridTextColumn. So the way to set the Mode at runtime is:

1    private void DataGrid1_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
2    {
3        DataGridTextColumn tc = (DataGridTextColumn)e.Column;
4        tc.Header = "Custom Header";
5        tc.Binding.Mode = BindingMode.TwoWay;
6    }

Now that I have TwoWay binding, I have to figure out how changes make it back to my BusinessObject.

John Mc
A: 

If the binding is correct your business objects will automatically receive the required updates. To do you binding programmatically you might need a little more code, something like:

...
Binding binding = new Binding("Propertyname");
tc.binding.Mode = BindingMode.TwoWay;
...
Mark Cooper