2010-08-18 61 views
3

我想遞歸綁定到TreeView中的項目的子項。從我在MSDN上可以看到的HierarchicalDataTemplate是要走的路,但到目前爲止,我只是部分成功。在WPF TreeView中遞歸綁定

我的類:

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
     DocumentText test = new DocumentText(); 
     this.DataContext = test; 

     for (int i = 1; i < 5; i++) 
     { 
      test.AddChild(); 
     } 
     foreach (DocumentText t in test.Children) 
     { 
      t.AddChild(); 
      t.AddChild(); 
     } 
    } 
} 

partial class DocumentText 
{ 
    private string _name; 
    public string Name 
    { 
     get { return _name; } 
     set { _name = value; } 
    } 

    public override string ToString() 
    { 
     return Name; 
    } 

    public List<DocumentText> _children; 
    public List<DocumentText> Children 
    { 
     get { return this._children; } 
    } 

    public DocumentText() 
    { 
     _name = "Test"; 
     _children = new List<DocumentText>(); 
    } 

    public void AddChild() 
    { 
     _children.Add(new DocumentText()); 
    } 
} 

我的XAML: 在mainview.xaml:

<Window x:Class="treetest.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <TreeView Name="binderPanel" DockPanel.Dock="Left" 
         MinWidth="150" MaxWidth="250" Background="LightGray" 
         ItemsSource="{Binding Children}"> 
     </TreeView> 
    </Grid> 
</Window> 

在App.xaml中:

<HierarchicalDataTemplate x:Key="BinderTemplate" 
DataType="{x:Type src:DocumentText}" ItemsSource="{Binding Path=/Children}"> 
      <TreeViewItem Header="{Binding}"/> 
     </HierarchicalDataTemplate> 

這段代碼產生的第一個列表孩子,但不顯示嵌套的孩子。

回答

4

你發佈的主要問題是你沒有連接HierarchicalDataTemplate作爲TreeView的ItemTemplate。您需要設置ItemTemplate="{StaticResource BinderTemplate}"或刪除x:Key以將模板應用於所有DocumentText實例。您還應該將模板中的TreeViewItem更改爲TextBlock - 將爲您生成TreeViewItem,並將該模板中的內容作爲HeaderTemplate應用於該模板。

+0

謝謝!那就是訣竅。我也不知道HeaderTemplate。 – Clay 2010-08-18 18:50:51

+1

我很驚訝你的解決方案有效,因爲你的對象不會引發屬性或集合更改的事件,並且在你填充它們的集合之前就綁定了它們。 – 2010-08-18 18:56:27

+0

@Robert - 我認爲這是因爲Binding不是在構造函數完成之後纔開始的,而是在InitializeComponent期間保存的。儘管需要更改通知+1。如果實現INotifyPropertyChanged並使用ObservableCollection而不是List,它將在以後節省很多挫折。 – 2010-08-18 21:40:19