walterhuang
walterhuang

Reputation: 632

Display master detail data in nested ListBox

I want to display my data like this

enter image description here

Here is the class definition:

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; }
}

I try to use ListBox but fail to display Details. Below is my try in 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>

in code behind:

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;
}

What is the correct way to bind OrderList.Details? Any suggestions will be appreciated.

Upvotes: 1

Views: 494

Answers (1)

Mohammad
Mohammad

Reputation: 1990

In your Order class Details is a field not a property. Binding to fields is not supported.

You can modify the class slightly so it becomes:

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>();
    }
}

And then it will bind correctly.

Upvotes: 2

Related Questions