如何在DataTable中横向展示List<int>元素并绑定到WPF DataGrid显示
问题根因
你当前的代码存在两个核心错误:
- 你为DataTable添加了
Num、Name、Test_1、Test_2、Test_3共5个列,但调用Rows.Add时仅传入了3个参数,等于把整个List<int>对象赋值给了Test_1列,后续两个Test_列完全没有赋值。 - DataGrid绑定DataTable时,遇到引用类型对象会默认调用
ToString()方法展示内容,所以才会输出System.Collections.Generic.List 1[System.Int32]的类型字符串;AutoGenerateColumns="True"仅会自动生成DataTable已定义的列,不会自动拆分你塞入的集合对象。
修复方案
你需要将List<int>中的元素逐个取出,分别填充到对应序号的Test_列中。如果需要兼容任意长度的List<int>,可以先计算所有集合的最大长度,再动态生成对应数量的列,最终逐列填充数值即可。
修改后的MainWindow.xaml.cs完整代码:
using System.Collections.Generic; using System.Data; using System.Linq; using System.Windows; namespace WpfApp1 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); // 构造CatModel数据源,可根据实际场景替换 List<CatModel> catList = new List<CatModel> { new CatModel(1, "AA", new List<int> { 1, 2, 3 }), new CatModel(2, "BB", new List<int> { 4, 5, 6 }), new CatModel(3, "CC", new List<int> { 7, 8, 9 }) }; DataTable result = new DataTable(); // 添加固定列 result.Columns.Add("Num", typeof(int)); result.Columns.Add("Name", typeof(string)); // 计算List的最大长度,动态生成Test列 int maxTestLength = catList.Max(c => c.Test_List.Count); for (int i = 0; i < maxTestLength; i++) { result.Columns.Add($"Test_{i + 1}", typeof(int)); } // 填充行数据 foreach (var cat in catList) { List<object> rowValues = new List<object> { cat.Num, cat.Name }; for (int i = 0; i < maxTestLength; i++) { // 长度不足的集合补空值 rowValues.Add(i < cat.Test_List.Count ? cat.Test_List[i] : System.DBNull.Value); } result.Rows.Add(rowValues.ToArray()); } DataContext = result; } } }
MainWindow.xaml和CatModel.cs不需要做任何修改,运行后就能看到List<int>的元素横向展开在DataGrid中。
内容的提问来源于stack exchange,提问作者IanHacker
相关产品推荐
相关产品推荐

