【问题标题】:TreeView and Entity Framework bindingTreeView 和实体框架绑定
【发布时间】:2012-02-28 12:21:33
【问题描述】:

我是 WPF 和 EF 的新手;我已经查看过,但找不到合适的帮助。


这就是我所拥有的:

实体框架ReportDefinition.ParentIDReportDefinition.SectionIDSection.idSections), ReportDefinition 示例Section示例

这就是我想介绍的:

树视图

.


我正在尝试以编程方式实现这一目标。非常感谢任何帮助。

【问题讨论】:

    标签: c# .net wpf linq entity-framework


    【解决方案1】:

    你需要一个顶级ReportDefinition对象的集合:

    TopLevelReportDefinitions = ReportDefinitions.Where(rd => rd.ParentID == 0)
    

    您需要将此集合绑定到TreeViewItemsSource

    在 EF 中,您还需要在 ReportDefinition 上创建父子关系,使用 ParentID 将子级链接到父级。为方便起见,您可以将反向集合命名为 Children。直接在另一个 ReportDefinition 下方的 ReportDefinition 对象的集合就是集合:

    ReportDefinition.Children
    

    然后您必须在TreeView 中创建HierarchicalTemplate

    <TreeView ItemsSource="{Binding TopLevelReportDefinitions}">
      <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
          <TextBlock Text="{Binding Name}"/>
        </HierarchicalDataTemplate>
      </TreeView.ItemTemplate>
    </TreeView>
    

    【讨论】:

    • 感谢您的回复,马丁。这就是我所做的:using (var context = new reportEntities(entityConnectionString)) { var TopLevelReportDefinitions = context.ReportDefinitions.Where(rd =&gt; rd.ParentID == 0); tvReport.ItemsSource = TopLevelReportDefinitions.ToList(); } 我还将建议的模板添加到 TreeView。不幸的是,我无法弄清楚如何创建父子关系。你能帮我解决这个问题吗?
    • @Yeseanul:一种选择是在数据库中创建关系(从 ParentID 到 idReportDefinition 的外键)。然后,如果您从数据库更新模型,我希望 EF 为模型中的关系创建属性。名称不会是 ParentChildren,但您可以重命名它们。
    • 我已经这样做了(在数据库中添加了一个外键并更新了模型)但没有成功。我最终扩展了 EF 创建的 public partial class ReportDefinition : EntityObject;所以我添加了一个属性public IList&lt;Section&gt; GetChildren。我也相应地更改了模板&lt;HierarchicalDataTemplate ItemsSource="{Binding GetChildren}"&gt;。这种方法确实提供了一些结果:TreeView 只显示孩子但不显示父母。另一个问题是,这并没有显示 Grand-Children,Grand-Grand-Children……对此有什么想法吗?
    • 好的,问题解决了。我所做的是向 EF public partial class ReportDefinition : EntityObject 创建的类添加两个属性:public IList&lt;ReportDefinition&gt; Childrenpublic string Name。这适用于答案中提供的 XML。感谢您的帮助。
    • @UB3571 public partial class ReportDefinition : EntityObject 由 EF 生成。作为部分类,您可以扩展它。因此,在您的代码中,只需声明一个 public partial class ReportDefinition 并添加您想要/需要的任何内容。就我而言,是上面提到的两个属性(我添加了更多,但这两个有助于解决我遇到的问题)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多