【问题标题】:Colorize Autogenerated Columns from DataTable in wpf DataGrid在 wpf DataGrid 中为 DataTable 中的自动生成的列着色
【发布时间】:2022-01-04 18:12:42
【问题描述】:

我目前正在创建一个带有(可选)列名的 DataTable,我将其加载到 DataGrid 中

List<string[]> ImportTable;
public void GeneratePreview()
{
    // Build datatable
    DataTable csvPreview = new DataTable();
    // generate Columns (with headers if selected)
    for (int i = 0; i < ImportTable[0].Length; i++)
    {
        csvPreview.Columns.Add();
        if ((bool)HasHeaders_Checkbox.IsChecked)
        {
            // specify table headers   
            csvPreview.Columns[i].ColumnName = ImportTable[0][i];
        }
    }
    /* Add records excluded here as not beneficiary for the question */
    // build display output
    this.ImportPreview.ItemsSource = csvPreview.AsDataView();
}

这用于预览 csv 数据、选择正确的拆分器、编码和指定列名。

到目前为止的预览看起来不错。标题在那里,数据在那里。

可能有很多电子废物列对我的项目没有好处,或者列的名称不一致,这取决于我要导入的银行对帐单。 因此我想标记导入的列。 我尝试了以下方法:

// ImportPreview is my Datagrid in WPF xaml
this.ImportPreview.Columns[index].CellStyle = new Style(typeof(DataGridCell));
this.ImportPreview.Columns[index].CellStyle.Setters.Add(new Setter(DataGridCell.BackgroundProperty, new SolidColorBrush(Colors.LightBlue)));

这在我手动添加列时有效。不考虑自动生成的列:

// Index was 1 and the DataGrid actually has 8 Columns

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index'

请帮助为自动生成的列着色。

【问题讨论】:

    标签: c# wpf colors datagrid


    【解决方案1】:

    将列添加到 DataTable 和 DataGrid 时,列得到正确映射:

    // generate Columns (with headers if selected)
    for (int i = 0; i < ImportTable[0].Length; i++)
    {
        csvPreview.Columns.Add();
        DataGridTextColumn col = new DataGridTextColumn();
        string columnName;
        if ((bool)HasHeaders_Checkbox.IsChecked)
        {
            // specify Column Name
            columnName = ImportTable[0][i];
        }
        else
        {
            // generate generic names
            columnName = "Column " + i;
        }
        csvPreview.Columns[i].ColumnName = columnName;
        col.Binding = new Binding(columnName);
        col.Header = columnName;
        this.ImportPreview.Columns.Add(col);
    }
    

    结果:

    注意:通用名称的生成对于映射列非常重要。如果未指定通用名称,则映射不正确,结果将如下所示:

    注2: AutoGenerateColumns="False" 应在 xaml 中设置为数据网格

    【讨论】:

    • "AutoGenerateColumns="False" 应该在 xaml 中设置为 DataGrid" - 为什么?将 CellStyle 添加到生成的列很简单,如下所示:stackoverflow.com/a/45774455/1506454
    • 否则它还会从 DataTable 中自动生成列,从而导致重复的列,例如 Column1; Column2; column3; Column1; Column2; Column3;
    • 如果您同时应用这两种解决方案,那么是的,您将拥有所需列的两个副本。我的观点是自动生成的列也可以自定义。并且它是 MVVM 兼容的
    • 我不知道该怎么做。但请随时发布答案。
    • 我发布了一个答案链接。这里的原理相同
    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 2012-04-24
    • 2011-08-07
    • 2014-03-12
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 2011-07-01
    相关资源
    最近更新 更多