It drives me crazy. I create a DataGrid in the code and then bind it to a datatable. This is dynamic, and the rows and columns will be different each time you create a grid.
Basically, I go through my datatable and create DataGrid columns for each column, for example:
private static void CreateDataGridColumns(DataGrid datagrid, Document doc) { if (doc == null) return;
As you can see, I use a custom data template selector so that I can render the cell differently depending on its contents.
Here is the pattern selector
public class CustomRowDataTemplateSelector : DataTemplateSelector { public override DataTemplate SelectTemplate(object item, DependencyObject container) { FrameworkElement element = container as FrameworkElement; var presenter = container as ContentPresenter; var gridCell = presenter.Parent as DataGridCell; if (element != null && item != null && gridCell != null) { var row = item as DataRow; if (row != null) { var cellObject = row[gridCell.Column.DisplayIndex];
Here is my stringCell DataTemplate
<DataTemplate x:Key="stringCell"> <StackPanel> <TextBlock Style="{StaticResource cellStyle}" Grid.Row="0" Grid.Column="0" Text="{Binding Converter={StaticResource cellConverter}}" /> </StackPanel> </DataTemplate>
The problem is that the template selector is called for each cell (as expected), but I canβt determine which cell it is, so I donβt know how to set the text in the TextBlock. I would like to do something like this
<DataTemplate x:Key="stringCell"> <StackPanel> <TextBlock Style="{StaticResource cellStyle}" Grid.Row="0" Grid.Column="0" Text="{Binding Path=Row[CellIndex], Converter={StaticResource cellConverter}}" /> </StackPanel> </DataTemplate>
But for me there is nothing available for CellIndex. How can I do something like this where I can set Path = Row [CellIndex]
source share