【发布时间】:2020-10-02 16:35:33
【问题描述】:
我正在尝试更改 DataGrid 内的单元格模板,具体取决于包含单元格类型的 List<List<int>>(即 1=bool、2=int、3=string、4=custom、等等...)。自定义类型(类型,因为它们可以超过 1 个)必须由 ComboBox 表示。对于数字和字符串,我需要一个普通的TextBox,对于布尔值,我需要一个CheckBox。 DataGrid 绑定到 DataTable,我可以在运行时调整和编辑它。这是一些代码:
<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 基本上是一个List<List<object>>,周围有一些实用方法。
我看到有一些解决方案,例如使用 DataTrigger,但我认为在这种情况下我需要在 XAML 文件中的DataGrid 中写入,但我不能因为AutoGenerateColumns 是True。还有可能更改DataTable 的每一列的类型,但我不希望该列的每个单元格都属于该类型,我希望在运行时只有一个单元格成为该类型。
也许有更好的解决方案,例如不使用DataGrid,或者不使用DataTable,或者有一种方法可以将AutoGenerateColumns 设置为False,并在需要时通过代码手动生成每一列.任何建议都非常感谢。
提前致谢。
【问题讨论】:
-
有事件拦截更改生成列:stackoverflow.com/a/40359000/1506454
-
是的,但我不希望以这种方式显示整个列。我只希望该列的 1 个单元格与其他单元格不同。
标签: c# wpf datatable binding datagrid