Reputation: 632
I want to display my data like this
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
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