C# 我的树景在哪里?
作为一个完整的WPF noob,我正在尝试使用AdventureWorks数据库的C# 我的树景在哪里?,c#,wpf,data-binding,treeview,wpf-controls,C#,Wpf,Data Binding,Treeview,Wpf Controls,作为一个完整的WPF noob,我正在尝试使用AdventureWorks数据库的HumanResources.emplopyee表,首先通过EF 5代码创建一个层次数据绑定“TreeView”。在完成一些示例之后,我提出了以下内容,在运行时生成一个完全空白的main窗口 <Window x:Class="FlatTree.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation
HumanResources.emplopyee
表,首先通过EF 5代码创建一个层次数据绑定“TreeView”。在完成一些示例之后,我提出了以下内容,在运行时生成一个完全空白的main窗口
<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 MainWindow()
{
InitializeComponent();
var ctx = new AdventureWorksContext();
Employees = TreeBuilder.BuildEmployeeTree(ctx.Employees);
DataContext = this;
}
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;
}
public MainWindow()
{
InitializeComponent();
var ctx = new AdventureWorksContext();
Employees = TreeBuilder.BuildEmployeeTree(ctx.Employees);
DataContext = this;
}