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

WPF中向DataGrid添加数据时显示List类型而非内容的问题求助

问题原因与解决方法

原因

你错误地将整个List<Invoice>集合作为单个元素添加到了DataGrid.Items中,DataGrid无法识别集合类型的项,因此直接输出了集合的类型字符串(就是你看到的System.Collections.Generic.List1[VoltageStablizer.EnterParams+Invoice]`)。

解决方法

根据你的需求,有三种可行的处理方式:

1. 仅添加单个Invoice对象(当前场景适用)

既然你的List里只有一个Invoice实例,直接创建单个对象并添加到Items即可:

Invoice newInvoice = new Invoice()
{
    Number = num,
    Item = equipment.Text,
    Power = power.Text,
    Quantity = quantity.Text
};
DataGrid.Items.Add(newInvoice);

2. 批量添加多个对象(或后续有批量需求)

如果需要一次性添加多个Invoice,使用AddRange方法将集合中的所有项批量加入:

List<Invoice> itemCollection = new List<Invoice>()
{
    new Invoice() { Number = num, Item = equipment.Text, Power = power.Text, Quantity = quantity.Text },
    // 可以继续添加更多Invoice实例
};
DataGrid.Items.AddRange(itemCollection);

3. 更符合WPF规范的数据绑定方式(推荐)

WPF更推荐通过数据绑定而非直接操作Items集合,这样能更好地处理数据更新和UI同步:

  • 首先在窗口类或ViewModel中定义ObservableCollection(集合变化时UI会自动更新):
    private ObservableCollection<Invoice> _invoiceList = new ObservableCollection<Invoice>();
    public ObservableCollection<Invoice> InvoiceList => _invoiceList;
    
  • 添加数据时直接往集合里加对象:
    _invoiceList.Add(new Invoice()
    {
        Number = num,
        Item = equipment.Text,
        Power = power.Text,
        Quantity = quantity.Text
    });
    
  • 在XAML中绑定DataGrid的ItemsSource:
    <DataGrid ItemsSource="{Binding InvoiceList}" AutoGenerateColumns="True"/>
    
  • 最后记得设置窗口的DataContext(比如在窗口构造函数里加DataContext = this;)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 22:42:42