I need to bind some data to a DataGrid with variable number of columns. I made it work using following code:
int n = 0;
foreach (string title in TitleList)
{
DataGridTextColumn col = new DataGridTextColumn();
col.Header = title;
Binding binding = new Binding(string.Format("DataList[{0}]", n++));
binding.Mode = BindingMode.TwoWay;
col.Binding = binding;
grid.Columns.Add(col);
}
where DataList is declared as:
public ObservableCollection<double> DataList { get; set; }
and TitleList is declared as:
public ObservableCollection<string> TitleList { get; set; }
The problem is that, even though I specified TwoWay binding, it is really one-way. When I click a cell to try to edit, I got an exception "'EditItem' is not allowed for this view". Did I just miss something in the binding expression?
P.S. I found an article from Deborah "Populating a DataGrid with Dynamic Columns in a Silverlight Application using MVVM". However, I had hard time to make it work for my case (specifically, I can't make the header binding work). Even if it worked, I'm still facing issues like inconsistent cell styles. That's why I'm wondering if I could make my above code work - with a little tweak?
EDIT: I found another post which might be related to my problem: Implicit Two Way binding. It looks if you bind to a list of string to a TextBox using
<TextBox Text="{Binding}"/>
You will get an error like "Two-way binding requires Path or XPath". But the problem can easily be fixed by using
<TextBox Text="{Binding Path=DataContext, RelativeSource={RelativeSource Self}}"/>
or
<TextBox Text="{Binding .}"/>
Can anybody give me a hint if my problem can be solved in a similar way?