2014-02-22 90 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