You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF动态生成列的DataGrid如何为每行各列填充唯一值

WPF动态生成DataGrid列并实现每行每列唯一值

问题核心

当前所有列绑定的都是实体类的同一个lol属性,导致所有列显示完全相同的内容。要实现每行每列展示唯一值,需要让每个列绑定到行数据中对应的独立字段。

解决方案

1. 修改实体类

将实体类改为支持存储多列数据的结构,用字典来映射列索引与对应值,适配动态列的场景:

internal class test
{
    // 键为列索引,值为该列对应内容
    public Dictionary<int, string> ColumnValues { get; set; } = new Dictionary<int, string>();
}

2. 初始化ViewModel集合

确保ViewModel中的tests集合已初始化,避免空引用:

internal class mainViewModel
{
    public ObservableRangeCollection<workerViewItem> workerViewItems { get; set; }
    public ObservableRangeCollection<workArea> workAreas { get; set; }
    public ObservableRangeCollection<test> tests { get; set; } = new ObservableRangeCollection<test>();
}

3. 方案一:使用模板列(支持自定义控件)

修改XAML模板列

调整绑定逻辑,通过RelativeSource获取列的索引标记,绑定到字典对应值:

<DataGrid Width="500" AutoGenerateColumns="False"
            x:Name="dataGrid"
            IsReadOnly="True"
            CanUserAddRows="False"
            CanUserDeleteRows="False"
            ItemsSource="{Binding tests}">
    <DataGrid.Resources>
        <DataGridTemplateColumn x:Key="TemplateColumn" x:Shared="False">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <!-- 绑定到当前行对应列索引的字典值 -->
                    <TextBlock Text="{Binding ColumnValues[ {Binding Tag, RelativeSource={RelativeSource AncestorType=DataGridColumn}} ]}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Resources>
</DataGrid>

修改后台生成代码

动态生成列时标记列索引,同时为每行的每个列赋值唯一内容:

private void CreateDataGridColumns()
{
    int columnCount = 10;
    // 生成动态列
    for (int i = 0; i < columnCount; i++)
    {
        DataGridTemplateColumn templateColumn = (DataGridTemplateColumn)dataGrid.Resources["TemplateColumn"];
        templateColumn.Header = $"Test {i + 1}";
        // 标记当前列的索引,供绑定使用
        templateColumn.Tag = i;
        dataGrid.Columns.Add(templateColumn);
    }
    // 生成每行数据,确保每列值唯一
    for (int rowIndex = 0; rowIndex < 10; rowIndex++)
    {
        var testItem = new test();
        for (int colIndex = 0; colIndex < columnCount; colIndex++)
        {
            testItem.ColumnValues[colIndex] = $"行{rowIndex+1}列{colIndex+1}";
        }
        _mainViewModel.tests.Add(testItem);
    }
}

4. 方案二:使用文本列(纯文本场景更简洁)

如果仅需显示文本,可直接使用DataGridTextColumn,无需模板列:

private void CreateDataGridColumns()
{
    int columnCount = 10;
    // 生成动态文本列
    for (int i = 0; i < columnCount; i++)
    {
        var textColumn = new DataGridTextColumn();
        textColumn.Header = $"Test {i + 1}";
        // 直接绑定到字典对应索引的值
        textColumn.Binding = new Binding($"ColumnValues[{i}]");
        dataGrid.Columns.Add(textColumn);
    }
    // 生成行数据
    for (int rowIndex = 0; rowIndex < 10; rowIndex++)
    {
        var testItem = new test();
        for (int colIndex = 0; colIndex < columnCount; colIndex++)
        {
            testItem.ColumnValues[colIndex] = $"R{rowIndex+1}C{colIndex+1}";
        }
        _mainViewModel.tests.Add(testItem);
    }
}

内容的提问来源于stack exchange,提问作者Emils Legzdins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 17:20:34