2010-08-18 6 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에서 는 :

은 app.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> 

는 :

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

이 코드는 최초의 목록을 생성 그러나 중첩 된 자식은 표시되지 않습니다.

답변

4

게시 한 주요 문제는 HierarchicalDataTemplate을 TreeView의 ItemTemplate으로 연결하지 않았다는 것입니다. 템플릿을 모든 DocumentText 인스턴스에 적용하려면 ItemTemplate="{StaticResource BinderTemplate}"을 설정하거나 x : Key를 제거해야합니다. 템플릿의 TreeViewItem을 TextBlock으로 변경해야합니다. TreeViewItem이 생성되고 템플릿에 넣은 내용이 HeaderTemplate으로 적용됩니다.

+0

고마워요! 그것은 트릭을했다. 나는 HeaderTemplate에 대해서도 몰랐다. – Clay

+1

개체가 속성 또는 컬렉션 변경 이벤트를 발생시키지 않고 컬렉션에 채우기 전에 바인딩 한 것이므로 솔루션이 작동하는 것이 놀랍습니다. –

+0

@ 로버트 - 바인딩은 InitializeComponent가 아니라 생성자가 완료 될 때까지 시작되지 않는다는 사실로 인해 저장되고 있다고 생각합니다. 변경 알림의 필요성에 +1. INotifyPropertyChanged를 구현하고 List 대신 ObservableCollection을 사용하면 나중에 많은 좌절감을 줄일 수 있습니다. –

관련 문제