Skip to main content
 首页 » 编程设计

c#之如何在 WPF 中将自定义对象绑定(bind)到列表框

2024年02月20日10exmyth

我是 WPF 的新手,所以如果我的问题很愚蠢,请接受我的道歉。

我正在创建一个食品订购系统,它由两个主要部分组成,即“食品菜单”和“订单列表”。当用户从食物菜单中选择一个项目时,它将被添加到表示订单列表的列表框控件中。

我创建了一些自定义对象:Order、OrderLine、Item,以及一个 Collection 类,OrderLineCollection,用于“OrderLine”。它们看起来像下面这样:

public class Order 
{ 
    public string ID { get; set; } 
    public DateTime DateTime { get; set; } 
    public double TotalAmt { get; set; } 
    public OrderLineCollection LineItems { get; set; } 
} 
 
public class OrderLine 
{ 
    public Item Item { get; set; } 
    public double UnitPrice { get; set; } 
    public int Quantity { get; set; } 
    public double SubTotal { get { return unitPrice * quantity; } } 
} 
 
[Serializable] 
public class OrderLineCollection : CollectionBase 
{ 
    public OrderLine this[int index] 
    { 
        get { return (OrderLine)List[index]; } 
        set { List[index] = value; } 
    } 
} 
 
public class Item 
{ 
    public string ID { get; set; } 
    public string Name { get; set; } 
    public string Description { get; set; } 
    public double UnitPrice { get; set; } 
    public byte[] Image { get; set; } 
} 

我的 ListBox 控件有一个 DataTemplate,以便显示每个项目的更多详细信息。 XAML 如下:

<Page x:Class="FoodOrdering.OrderList" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      Title="Order List"> 
    <ListBox Name="lbxOrder" HorizontalContentAlignment="Stretch">             
        <ListBox.ItemTemplate> 
            <DataTemplate> 
                <Grid Margin="5"> 
                    <Grid.ColumnDefinitions> 
                        <ColumnDefinition Width="*"/> 
                        <ColumnDefinition Width="30"/> 
                        <ColumnDefinition Width="80"/> 
                    </Grid.ColumnDefinitions> 
                    <Grid.RowDefinitions> 
                        <RowDefinition/> 
                        <RowDefinition Height="40"/> 
                    </Grid.RowDefinitions> 
                    <TextBlock Grid.Row="0" Grid.Column="0" Grid.RowSpan="2" Text="{Binding item.name}"/> 
                    <TextBlock Grid.Row="0" Grid.Column="1" Text="x "/> 
                    <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding quantity}" Margin="10,0,0,0"/> 
                    <TextBlock Grid.Row="0" Grid.Column="2" Text="{Binding subTotal, Converter={StaticResource priceConverter}}" HorizontalAlignment="Right"/> 
                    <Button Grid.Row="1" Grid.Column="2" Margin="0,5,0,0" Click="btnDelete_Click">Delete</Button> 
                </Grid> 
            </DataTemplate> 
        </ListBox.ItemTemplate> 
    </ListBox> 
</Page> 

所以当添加项目时,ListBox 将如下图所示: https://dl.dropbox.com/u/6322828/orderList.png

在代码隐藏中,我创建了一个静态变量currentOrder 用于存储当前订单,它将被其他类/方法使用。

每次它的值改变时,都会调用以下愚蠢的方法LoadCurrentOrder() 来刷新ListBox View 。

public partial class OrderList : Page 
{ 
    public static Order currentOrder = new Order(); 
    public OrderList() 
    { 
        InitializeComponent(); 
        LoadCurrentOrder(); 
    } 
 
    public void LoadCurrentOrder() 
    { 
        lbxOrder.Items.Clear(); 
        foreach (OrderLine ol in currentOrder.LineItems) 
            lbxOrder.Items.Add(ol); 
    } 
} 

我的问题是如何以优雅的方式绑定(bind)数据(例如使用 Resources ItemsSource 等)而不是使用上述方法,以便每当变量的值改变时,ListBox 会自动更新吗?

我试过了

lbxOrder.ItemsSource = currentOrder;  

但它不起作用,因为 currentOrder 不是 System.Collections.IEnumerable 对象。

请您参考如下方法:

1 - 不要创建您自己的集合类型,.Net 框架基类库已经拥有您需要的几乎所有内容。

删除 OrderLineCollection并使用 ObservableCollection<OrderLine> .

2 - 尽量遵守 MVVM 约定。这意味着您不应在代码中操作 UI 元素。

public OrderList() 
{ 
    InitializeComponent(); 
    LoadCurrentOrder(); 
    DataContext = this; 
} 

然后在 XAML 中:

<ListBox ItemsSource="{Binding LineItems}" HorizontalContentAlignment="Stretch"> 

3 - 不要在 XAML 中命名 UI 元素,除非您需要在 XAML 中引用它们。每当您发现自己想要在过程代码中操作 UI 元素时,这将帮助您重新考虑您的方法。

4 - 习惯 C# 命名约定。属性名称应该是“适当的大小写”(即 LineItems 而不是 lineItems )