2010-08-18 65 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