0

我正在尝试 - 作为一个完整的 WPF 菜鸟 -HumanResources.Emplpoyee通过 EF 5 Code First 使用 AdventureWorks DB 的表创建一个分层数据绑定的“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工作,并将 Employee 实体列表及其ManagerIdSubordinates(从 重命名Employee1)属性转换为树模型,如下所示:

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;
}

我没有做什么,或者做错了什么?

4

1 回答 1

0

你还没有设置DataContext你的Window,你可以在初始化后在构造函数中设置它

public MainWindow()
{
    InitializeComponent();
    var ctx = new AdventureWorksContext();
    Employees = TreeBuilder.BuildEmployeeTree(ctx.Employees);
    DataContext = this;
}
于 2013-10-13T09:51:34.413 回答