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

如何在WPF DataGrid中用C#双向绑定显示列头与多行数据列表

在WPF DataGrid中绑定动态列头与数据的实现方案

核心思路

嘿,我来帮你搞定这个动态数据绑定的问题!WPF的DataGrid默认更适配强类型对象,但咱们手里的列头和行都是动态字符串列表,所以用DataTable当中间载体是最省心的选择——它能动态创建列来匹配咱们的表头,还能轻松填充行数据,天然支持双向绑定,完美适配需求。

具体实现步骤

1. 后台代码:把列头和行数据转成DataTable

先把咱们的原始数据转换成DataTable,这样才能和DataGrid无缝对接:

using System.Data;
using System.Collections.Generic;

// 你的原始数据
List<string> headers = new List<string> { "FirstName", "LastName", "Age" };
List<string> row1 = new List<string> { "John", "Doe", "19" };
List<string> row2 = new List<string> { "Jane", "Doe", "21" };
List<string> row3 = new List<string> { "Suzie", "Q", "52" };
List<string> row4 = new List<string> { "No", "Body", "48" };
List<List<string>> allRows = new List<List<string>> { row1, row2, row3, row4 };

// 创建DataTable并添加列
DataTable dataTable = new DataTable();
foreach (string header in headers)
{
    dataTable.Columns.Add(header, typeof(string));
}

// 填充所有行数据
foreach (List<string> row in allRows)
{
    dataTable.Rows.Add(row.ToArray());
}

// 绑定到DataGrid(假设你的DataGrid命名为dynamicDataGrid)
dynamicDataGrid.ItemsSource = dataTable.DefaultView;

2. XAML代码:配置DataGrid开启双向绑定

在XAML里设置DataGrid的属性,让它自动生成列并支持双向编辑:

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Dynamic DataGrid Demo" Height="450" Width="800">
    <Grid>
        <DataGrid x:Name="dynamicDataGrid"
                  AutoGenerateColumns="True"
                  CanUserAddRows="False"
                  CanUserDeleteRows="False"
                  IsReadOnly="False">
            <!-- 自动生成的列默认会开启双向绑定,因为DataView实现了属性变更通知 -->
        </DataGrid>
    </Grid>
</Window>

关键细节说明

  • 为什么选DataTable?:它能动态创建列适配咱们的表头,而且DataView(也就是dataTable.DefaultView)实现了INotifyCollectionChanged和INotifyPropertyChanged接口,天然支持WPF的双向绑定——用户编辑单元格内容时,DataTable里的数据会自动同步更新。
  • 双向绑定生效条件:一定要把IsReadOnly设为False,这样用户才能编辑单元格;如果不需要新增/删除行,就把CanUserAddRows和CanUserDeleteRows设为False避免误操作。
  • 如果想自定义列样式,把AutoGenerateColumns设为False,手动创建DataGridTextColumn并设置Binding="{Binding 列名, Mode=TwoWay}"就行。

内容的提问来源于stack exchange,提问作者Jarad Mayers

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:01:19