我是 WPF 的新手,我只是设法将特定类项的列表绑定到 ListBox。ListBox 现在成功地显示它们。这是一些代码,首先是类:
public class OrderItem
{
public int Quantity { get; set; }
public string Name { get; set; }
public Double Price { get; set; }
}
一些虚拟数据和绑定,这一切都发生在主程序的构造函数中:
List<OrderItem> currentOrderItems = new List<OrderItem>();
currentOrderItems.Add(new OrderItem() { Quantity = 5, Name = "Test", Price = 5 });
currentOrderItems.Add(new OrderItem() { Quantity = 15, Name = "Test test", Price = 6.66 });
currentOrderItems.Add(new OrderItem() { Quantity = 1, Name = "Test 3", Price = 15.88 });
listOrderItems.ItemsSource = currentOrderItems;
和 XAML:
<ListBox HorizontalAlignment="Left" Margin="150,27,0,23" Name="listOrderItems" Width="150" FontFamily="Times New Roman" FontSize="12">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="4">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Quantity}" FontWeight="Bold" />
<TextBlock Grid.Column="1" Text="{Binding Name }" />
<TextBlock Grid.Column="2" Text="{Binding Price }" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我的问题是如何更新 ListBox 以显示我添加到包含数据(即 OrderItems)的列表中的新项目。如果我以任何方式添加、删除或修改列表,这不会反映在 ListBox 中。谢谢!