Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我的树景在哪里?_C#_Wpf_Data Binding_Treeview_Wpf Controls - Fatal编程技术网

C# 我的树景在哪里?

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

作为一个完整的WPF noob,我正在尝试使用AdventureWorks数据库的
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;
}