I'm trying to change the template of a cell inside a DataGrid
depending on a List<List<int>>
which holds the type of the cell (I.e 1=bool, 2=int, 3=string, 4=custom, etc...). The custom types (types because they can be more than 1) have to be represented by a ComboBox
. For numbers and strings, I need a normal TextBox
and for boolean I need a CheckBox
. The DataGrid
is binded to a DataTable
which I can resize and edit at runtime. Here it is some code:
<Grid>
<DataGrid ItemsSource="{Binding Path=DataTable}" Name="Grid" AutoGenerateColumns="True"
CanUserResizeRows="True" CanUserDeleteRows="False"
CanUserAddRows="False" AreRowDetailsFrozen="False"
SelectionUnit="Cell" LoadingRow="Grid_LoadingRow">
<DataGrid.Style>
<Style TargetType="DataGrid">
<Setter Property="AlternatingRowBackground" Value="LightYellow"/>
</Style>
</DataGrid.Style>
</DataGrid>
</Grid>
public partial class TableEditorWindow : Window
{
public string[] DebugNames = { "Bob", "Dan", "Pierre", "Mark", "Gary" };
// Stores the values of the Table
public ds_grid Table { get; set; }
// Stores the types of each cell in the Table
public ds_grid ValueTypesTable { get; set; }
// Used as wrapper between the Table variable and the DataGrid
public DataTable DataTable { get; set; }
public TableEditorWindow()
{
InitializeComponent();
Table = new ds_grid(5, 5);
// Fills the Table with 1s
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < Table.Width; ++j)
{
Table.Set(i, j, 1d);
}
}
DataTable = new DataTable();
// Add the columns
for (int i = 0; i < 5; ++i)
{
DataTable.Columns.Add(DebugNames[i]);
}
// Add the rows
for (int i = 0; i < Table.Height; ++i)
{
DataRow _row = DataTable.NewRow();
for (int j = 0; j < Table.Width; ++j)
{
_row[j] = Table.Get(j, i);
}
DataTable.Rows.Add(_row);
}
Grid.DataContext = this;
Grid.RowHeaderWidth = 50;
Grid.ColumnWidth = 100;
}
// Gives to each row the correct name
private void Grid_LoadingRow(object sender, DataGridRowEventArgs e)
{
int _id = e.Row.GetIndex();
e.Row.Header = DebugNames[_id];
}
}
ds_grid
is basically a List<List<object>>
with some utility methods around it.
I saw that there are some solutions, such as using DataTrigger, but I think that in that case I'd need to write in in the DataGrid
in the XAML file, but I can't because AutoGenerateColumns
is True
. There is also the possibility to change the Type of each column of the DataTable
but I don't want that every cell of that column is of that type, I want that only a single cell becomes of that type, at runtime.
Maybe there are better solutions, such as not using a DataGrid
, or not using a DataTable
, or there is a way to set AutoGenerateColumns
to False
and manually generating every column when needed, by code. Any suggestion is really appreciated.
Thanks in advance.