I do not want use class properties for binding.
Why it doesn’t work? How I can fix this. I get empty rows. I have also manually defined columns for DataGrid.
private void Insert(IList<string> row, DataGrid dG)
{
ObservableCollection<IList<string>> data = dG.ItemsSource as ObservableCollection<IList<string>>;
data.Add(row);
dG.ItemsSource = data;
}
First of all, if you’re using methods to access directly to your DataGrid properties instead of using data binding, then you should use the DataGrid.Items property, not DataGrid.ItemsSource.
But you’ll get empty rows anyway, because the DataGrid has no way of linking each string in your row with the correct column definition.
I think the best approach would be using a converter:
Create the RowIndexConverter class inheriting from IValueConverter, and make so your Convert method looks like this:
For this to work, you have to use it in a Binding to an IList property, like the rows of our DataGrid, and pass an index as the ConverterParameter. The XAML would be something like this:
Et voila! The values show up. If you want more columns you just have to add them and increment the ConvertParameter. Be careful, as the converter will throw an Exception if the row is not long enough!