在嵌套的ListBox中显示主详细信息数据

时间:2013-01-21 08:20:00

标签: c# wpf binding

我想像这样显示我的数据

enter image description here

这是类定义:

public class Order
{
    public string Customer { get; set; }
    public decimal Amount { get; set; }
    public List<OrderDetail> Details = new List<OrderDetail>();
}

public class OrderDetail
{
    public string Product { get; set; }
    public int Qty { get; set; }
}

我尝试使用ListBox但无法显示详细信息。以下是我在xaml中的尝试:

<ListBox x:Name="lstOrder">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Customer}"/>
                <TextBlock Text="{Binding Amount}"/>
                <ListBox ItemsSource="{Binding Details}">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding Product}"/>
                                <TextBlock Text="{Binding Qty}"/>
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
代码背后的

public MainWindow()
{
    InitializeComponent();

    List<Order> OrderList = new List<Order>();
    Order order = new Order { Customer = "David", Amount = 2000 };
    order.Details.Add(new OrderDetail { Product = "A", Qty = 5 });
    OrderList.Add(order);

    order = new Order { Customer = "John", Amount = 5000 };
    order.Details.Add(new OrderDetail { Product = "A", Qty = 2 });
    order.Details.Add(new OrderDetail { Product = "B", Qty = 3 });
    OrderList.Add(order);

    lstOrder.ItemsSource = OrderList;
}

绑定OrderList.Details的正确方法是什么?任何建议将不胜感激。

1 个答案:

答案 0 :(得分:2)

Order班级Details中,字段不是属性。不支持绑定到字段。

您可以稍微修改该类,使其变为:

public class Order
{
    public string Customer { get; set; }
    public decimal Amount { get; set; }

    List<OrderDetail> details;
    public List<OrderDetail> Details { get { return details; } }

    public Order()
    {
        details = new List<OrderDetail>();
    }
}

然后它会正确绑定。