我正在尝试 - 作为一个完整的WPF菜鸟 - 使用AdventureWorks数据库的HumanResources.Emplpoyee
表,通过EF 5 Code First创建一个分层数据绑定'TreeView'。在按照一些例子后,我想出了以下内容,在运行时会产生一个完全空白的MainWindow
。
<Window x:Class="FlatTree.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:models="clr-namespace:AdventureWorks.Models;assembly=AdventureWorks"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TreeView DataContext="{Binding}" ItemsSource="{Binding Employees}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Subordinates}" DataType="{x:Type models:Employee}">
<TreeViewItem Header="{Binding Title}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
</Window>
和
public partial class MainWindow : Window
{
public IEnumerable<Employee> Employees { get; set; }
public MainWindow()
{
InitializeComponent();
var ctx = new AdventureWorksContext();
Employees = TreeBuilder.BuildEmployeeTree(ctx.Employees);
}
}
BuildEmployeeTree
可以使用ManagerId
和Subordinates
(从Employee1
重命名)属性将Employee实体列表转换为树模型,如下所示:
public static IEnumerable<Employee> BuildEmployeeTree(IEnumerable<Employee> employees)
{
var flatTree = employees.ToList();
foreach (var emp in employees)
{
if (emp.ManagerID != null)
{
var manager = flatTree.Single(e => e.EmployeeID == emp.ManagerID);
manager.Subordinates.Add(emp);
}
}
return flatTree;
}
我不做什么或做错了什么?
答案 0 :(得分:0)
您尚未设置DataContext
的{{1}},可以在初始化后在构造函数中设置
Window