2014-02-22 89 views
1

我想要在树视图中可视化对象的层次结构。我知道有很多教程介绍如何做到这一点。原则上我想我甚至知道该怎么做,但我被卡住了。我希望有人能指出我的错误。树视图中的分层结构(C#)

这是 “myObject的”:

private int _id; 
    public virtual int Id 
    { 
     get 
     { 
      return this._id; 
     } 
     set 
     { 
      if(this._id != value) 
      { 
       this.OnPropertyChanging("Id"); 
       this._id = value; 
       this.OnPropertyChanged("Id"); 
      } 
     } 
    } 

    private string _name; 
    public virtual string name 
    { 
     get 
     { 
      return this._name; 
     } 
     set 
     { 
      if(this._name != value) 
      { 
       this.OnPropertyChanging("name"); 
       this._name = value; 
       this.OnPropertyChanged("name"); 
      } 
     } 
    } 

    private int? _parentId; 
    public virtual int? parentId 
    { 
     get 
     { 
      return this._parentId; 
     } 
     set 
     { 
      if(this._parentId != value) 
      { 
       this.OnPropertyChanging("parentId"); 
       this._parentId = value; 
       this.OnPropertyChanged("parentId"); 
      } 
     } 
    } 

    private MyObject _myObject1; 
    public virtual MyObject MyParentObject 
    { 
     get 
     { 
      return this._myObject1; 
     } 
     set 
     { 
      if(this._myObject1 != value) 
      { 
       this.OnPropertyChanging("MyParentObject"); 
       this._myObject1 = value; 
       this.OnPropertyChanged("MyParentObject"); 
      } 
     } 
    } 

    private IList<MyObject> _myObjects = new List<MyObject>(); 
    public virtual IList<MyObject> MyChildObjects 
    { 
     get 
     { 
      return this._myObjects; 
     } 
    } 

这里最重要的是所谓的 “MyChildObjects” 子对象的列表。

的XAML如下所示:现在

<TreeView ItemsSource="{Binding myObjects}"> 
     <TreeView.ItemTemplate> 
      <HierarchicalDataTemplate ItemsSource="{Binding myObjects/MyChildObjects}"> 
       <TextBlock Text="{Binding name}" /> 
      </HierarchicalDataTemplate> 
     </TreeView.ItemTemplate> 
    </TreeView> 

我的问题是树形视图只显示所有对象的平面结构。最可能的错误是在XAML文件中,但我无法弄清楚。我必须改变树视图中的层次结构?

谢谢你的帮助! 致以问候

回答

1

尝试在TreeView.Resources定义你HierarchicalDataTemplateDataTypeMyObject的:

<TreeView ItemsSource="{Binding myObjects}"> 
    <TreeView.Resources> 
     <HierarchicalDataTemplate DataType="{x:Type local:MyObject}" ItemsSource="{Binding MyChildObjects}"> 
     <TextBlock Text="{Binding name}" /> 
     </HierarchicalDataTemplate> 
    </TreeView.Resources> 
</TreeView> 

也是你ItemsSource路径是错误的。当您使用myObjects/时,表示当前项目为myObjects。你需要的仅仅是ItemsSource="{Binding MyChildObjects}

Binding.Path

当源是一家集认为,目前的项目可以以斜杠(/)来指定。例如,子句Path = /设置绑定到视图中的当前项目。当源是集合时,此语法指定默认集合视图的当前项目。

+0

在这种情况下(其中treeview将包含单一类型的实例)需要'DataType'吗? – mcwyrm

+1

当您在'Resources'中指定'DataTemplate'时,您必须指定'DataType'或'x:Key' – dkozl

0

您已经设置了ItemsSource,但我认为您还需要在HierachicalDataTemplate中设置一个ItemTemplate。看看here