ListView中的WPF ListView [英] WPF ListView within a ListView
问题描述
我确定我缺少简单/显而易见的内容,但似乎无法将ListView的数据绑定到ListView中
I am sure I am missing something simple/obvious, but I cannot seem to bind the data of a ListView within a ListView
<Window x:Class="TestList.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate x:Key="InsideListTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="test" Width="50"></TextBlock>
<TextBlock Text="{Binding OrderId}" Width="50"></TextBlock>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="OrdersTemplate">
<ListView HorizontalAlignment="Stretch"
HorizontalContentAlignment="Stretch"
MinWidth="100"
MinHeight="25"
ItemsSource="{Binding Orders}"
ItemTemplate="{StaticResource InsideListTemplate}"
>
</ListView>
</DataTemplate>
<DataTemplate x:Key="CustomersTemplate">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch">
<TextBlock Text="{Binding CustomerId}" Width="50" Foreground="Navy" VerticalAlignment="Center" />
<ListBox ItemsSource="{Binding Orders}" ItemTemplate="{StaticResource OrdersTemplate}" HorizontalContentAlignment="Stretch"></ListBox>
</StackPanel>
</DataTemplate>
</Window.Resources>
<DockPanel LastChildFill="True">
<ListView Name="listView" ItemTemplate="{StaticResource CustomersTemplate}" >
</ListView>
</DockPanel>
using System.Collections.Generic;
namespace TestList
{
public partial class MainWindow
{
public class Customer
{
public int CustomerId { get; set; }
public List<Order> Orders { get; set; }
}
public class Order
{
public int OrderId { get; set; }
}
public MainWindow()
{
InitializeComponent();
DataContext = this;
var customers = new List<Customer>
{
new Customer
{
CustomerId = 1,
Orders = new List<Order>
{
new Order {OrderId = 1},
new Order {OrderId = 2}
}
},
new Customer
{
CustomerId = 2,
Orders = new List<Order>
{
new Order {OrderId = 1},
new Order {OrderId = 2}
}
}
};
listView.ItemsSource = customers;
}
}
}
推荐答案
此是对Hadis答案的解释:
This is an explanation of Hadis answer:
您要将 ListBox
绑定到 Orders
客户模板中的集合。然后,在订单模板中,您再次定义 ListView
绑定到订单。这意味着此时的绑定路径是不存在的customer.orders.orders。
You are binding a ListBox
to the Orders
collection within the customer template. And then in the orders template you define a ListView
binding again to the orders. This means that the binding path at that point is customer.orders.orders which does not exists.
如果仅删除 OrdersTemplate
并将 ListView
放在 ListBox
在客户模板中的位置,然后它就可以工作。
If you just remove the OrdersTemplate
and place the ListView
where the ListBox
is in the customer template then it works.
这篇关于ListView中的WPF ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!