2016-06-01 84 views
0

我需要綁定遞歸子節點在WPF樹視圖。但我真的不知道如何使它工作。這裏是我發現綁定多個層次結構數據WPF

ObservableCollection<Animal> animals = new ObservableCollection<Animal>(); 
animals.Add(new Animal("California Newt")); 
animals.Add(new Animal("Tomato Frog")); 
animals.Add(new Animal("Green Tree Frog")); 
animals.Add(new Animal("Frog")); 
AnimalCategories.Add(new AnimalCategory("Amphibians", animals)); 

animals = new ObservableCollection<Animal>(); 
animals.Add(new Animal("Golden Silk Spider")); 
animals.Add(new Animal("Black Widow Spider")); 
AnimalCategories.Add(new AnimalCategory("Spiders", animals)) 

列出需要要在樹視圖綁定和這裏爲它

AnimalCategory類結構:

Class AnimalCategory 
    Private _category As String 
    Public Property Category As String 
     Get 
      Return _category 
     End Get 
     Set(ByVal value As String) 
      _category = value 
     End Set 
    End Property 
    Private _animals As ObservableCollection(Of Animal) 
    Public ReadOnly Property Animals() As ObservableCollection(Of Animal) 
     Get 

      If _animals Is Nothing Then 
       _animals = New ObservableCollection(Of Animal)() 
      End If 

      Return _animals 
     End Get 
    End Property 

    Public Sub New() 
    End Sub 
    Public Sub New(category As String, animals As ObservableCollection(Of Animal)) 
     _category = category 
     _animals = animals 
    End Sub 
End Class 

動物類:

Class Animal 
    Private _name As String 
    Public Property Name As String 
     Get 
      Return _name 
     End Get 
     Set(ByVal value As String) 
      _name = value 
     End Set 


    End Property 
    Public Sub New() 
    End Sub 
    Public Sub New(name As String) 
     _name = name 
    End Sub 
End Class 

和我的xaml代碼是..!

<TreeView x:Name="radTreeView" Background="#4E4E4E" x:FieldModifier="public" ItemsSource="{x:Static local:cntlWPFMMTreeView.AnimalCategories}" 
     ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible"> 
<telerik:RadTreeView.ItemTemplate> 
     <HierarchicalDataTemplate ItemsSource="{Binding Animals}"> 
      <TextBlock Text="{Binding Category}" /> 
      <HierarchicalDataTemplate.ItemTemplate> 
       <DataTemplate> 
        <TextBlock Text="{Binding Name}"/> 
       </DataTemplate> 
      </HierarchicalDataTemplate.ItemTemplate> 
     </HierarchicalDataTemplate> 
    </telerik:RadTreeView.ItemTemplate> 
</TreeView> 

使用上面的代碼,我可以綁定父子hiereachy類似下面的一個級別,

enter image description here

BUIT我需要得到綁定類似像下面動態

多層次結構的

enter image description here

如何在WPF ..?

回答

0

你可以用另一種的DataContext控制的一個控件的值綁定原樣

綁定=「{綁定路徑= DataContext.MyBindingProperty,的ElementName = MyMainWindow}

修改這條線,按您的。要求

希望它可以幫助

+1

對不起,我無法得到它..! – Arshad

+0

這個綁定會對分層視圖做什麼? –

0

兩件事情: 您必須添加動物到你的動物級的ObservableCollections。而且您必須將HierarchicalDataTemplate的ItemTemplate更改爲另一個具有ItemsSource =「{Binding Animals}」的HierarchicalDataTemplate。