我决定做一个关于电压稳定器的小项目。我尝试将数据从 ComboBox 插入到 WPF 中的 DataGrid。
我创建了发票类:
public class Invoice
{
public string Number { get; set; }
public string Item { get; set; }
public string Power { get; set; }
public string Quantity { get; set; }
}
我使用列表将信息插入到 DataGrid。
List<Invoice> ItemCollection = new List<Invoice>()
{
new Invoice() {Number = num, Item = equipment.Text, Power = power.Text, Quantity = quantity.Text}
};
DataGrid.Items.Add(ItemCollection);
但是如果我将设备、功率和数量 ComboBoxex 数据打印到 DataGrid 中,我会得到错误的结果:
System.Collections.Generic.List`1[VoltageStablizer.EnterParams+Invoice]
DataGrid.Items
中的项目类型是DataGridItem这意味着您不能直接添加另一个不同类型的集合。
另一方面,将
IEnumerable
(在您的情况下为 ItemCollection
)分配给 DataGrid.ItemSource
会自动生成 DataGrid
的列。
向列表添加新项目时,只需将其添加到
ItemCollection
即可。还要在容器中为 ItemCollection
创建一个属性,以便您可以在代码的不同部分中使用。
// When initializing your container
ItemCollection = new List<Invoice>();
DataGrid.ItemSource = ItemCollection;
// When add button clicked
Itemcollection.Add(new Invoice() {Number = num, Item = equipment.Text, Power = power.Text, Quantity = quantity.Text});