0

In a loop which sets up my WPF DataGrid columns, I want to bind the column visibility to member 'i' in my 'VisibilityList' with the following code:

var bindingColumnVisibilty = new Binding(string.Format("VisibilityList[{0}]", i));
BindingOperations.SetBinding(customBoundColumn, DataGridColumn.VisibilityProperty, bindingColumnVisibilty);

I have set the DataContext before the loop begins:

TestControlDataGrid.TestDataGrid.DataContext = dataGridSource;

The dataGridSource class contains:

public List<Visibility> VisibilityList;

This does not appear to work. Have I set up my DataContext and binding correctly? Does it matter that after this loop I set the ItemsSource with the following?

TestDataGrid.ItemsSource = dataGridSource.DataList;
Caustix
  • 569
  • 8
  • 26
  • See the following link, the problem is explained: http://stackoverflow.com/questions/502389/binding-in-a-wpf-data-grid-text-column – Fredrik Hedblad Oct 03 '11 at 18:52
  • I used code-behind and updated visibility manually on property changed: http://stackoverflow.com/questions/4019236/bind-datagrid-column-to-viewmodel-property/4019688#4019688 – vortexwolf Oct 03 '11 at 19:51
  • I believe the problem is that the columns collection doesn't naturally inherit from the datagrid's datacontext. I'm going to do some research and will report back.. – Caustix Oct 04 '11 at 04:54

2 Answers2

1

You format the VisabilityList to string. You need to leave it as Visibility.

paparazzo
  • 44,497
  • 23
  • 105
  • 176
  • but if I try: var bindingColumnVisibilty = new Binding(dataGridSource.VisibilityList[i]); then gives me error "The best overloaded method match for 'System.Windows.Data.Binding.Binding(string)' has some invalid arguments" and "Argument 1: cannot convert from 'System.Windows.Visibility' to 'string'" – Caustix Oct 03 '11 at 21:12
0

Ok, it turns out that DataGridColumn does not inherit the DataContext from the DataGrid since it is not in the logical (or visual) tree, so that's why my binding doesn't work.

One workaround is shown here

Caustix
  • 569
  • 8
  • 26