I am having trouble getting a cell template to work with a DatagridTemplateColumn. The displayed output shows all columns filled with the data from the first column for each row.
If I set the cell's text binding to {Binding [2].Text}, it shows the data for the 3rd column in all columns, so I think I need some way in the cell template to get the index. I've tried setting the binding to {Binding [{DisplayIndex}].Text}, but then I get " BindingExpression path error: '[]' property not found on 'object'"
PS: I have to use a DataGridTemplateColumn because I will be doing more complicated displays in the future.
Here is the relevant xaml:
<DataGrid ItemsSource="{Binding TableItems}" AutoGenerateColumns="False" >
<DataGrid.Resources>
<DataTemplate x:Key="MyCellTemplate" >
<TextBlock Text="{Binding Text}" />
</DataTemplate>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTemplateColumn CellTemplate="{StaticResource MyCellTemplate}" Header="Col1" />
<DataGridTemplateColumn CellTemplate="{StaticResource MyCellTemplate}" Header="Col2" />
<DataGridTemplateColumn CellTemplate="{StaticResource MyCellTemplate}" Header="Col3" />
</DataGrid.Columns>
</DataGrid>
Binding Data:
public ObservableCollection<string[]> TableItems { get; set; }
...
TableItems.Add(new string[]{"A","B","C"};
TableItems.Add(new string[]{"D","E","F"};
TableItems.Add(new string[]{"G","H","I"};
When I run my program, The data for all the columns is the same as the first column in each row. e.g.:
Starting data:
A,B,C
D,E,F
G,H,I
Resulting output:
A,A,A
D,D,D
G,G,G
Expected output:
A,B,C
D,E,F
G,H,I
EDIT: -----------------------------------
A little more information: THis xaml works, but obviously I would like to employ a common cell template.
<DataGrid.Columns>
<DataGridTemplateColumn Header="col1" > <DataGridTemplateColumn.CellTemplate> <DataTemplate><TextBlock Text="{Binding [0].Text}" /></DataTemplate></DataGridTemplateColumn.CellTemplate></DataGridTemplateColumn>
<DataGridTemplateColumn Header="col2" > <DataGridTemplateColumn.CellTemplate> <DataTemplate><TextBlock Text="{Binding [1].Text}" /></DataTemplate></DataGridTemplateColumn.CellTemplate></DataGridTemplateColumn>
<DataGridTemplateColumn Header="col3" > <DataGridTemplateColumn.CellTemplate> <DataTemplate><TextBlock Text="{Binding [2].Text}" /></DataTemplate></DataGridTemplateColumn.CellTemplate></DataGridTemplateColumn>
</DataGrid.Columns>