2011-03-24 115 views
4

我有這樣一個類(介紹C#類及其字段,方法等):WPF XAML - TreeView的分層數據模板 - 多個項目源

public class CSharpType 
{ 
    public string Name { get; private set; } 
    public List<CSharpMethod> Methods { get; private set; } 
    public List<CSharpField> Fields { get; private set; } 
    public List<CSharpProperty> Properties { get; private set; } 
    .... 
} 

CShartpType的集合中的返回:

public List<CSharpType> TypeCollection 
    { 
     get 
     { 
      TypeCollection kolekcjaTypow = metricsCollection.Types; 
      Dictionary<string, CSharpType> typy = kolekcjaTypow.TypeDictionary; 
      var result = typy.Values.ToList(); 
      return result; 
     } 
    } 

各個領域,方法,屬性有一個 「名稱」 屬性 ,我想有TreeView控件(如):

Person 
    + Fields 
     + field1 name from Fields collection 
     + field2 name from Fields collection 
     ... 
    + Methods 
     .... 
    + Properties 

sholud xaml看起來像什麼樣子?感謝您的幫助

+0

有你看了樣品XAML在http://msdn.microsoft.com/en-us/library/system.windows.hierarchicaldatatemplate.aspx ? – 2011-03-24 22:57:27

+0

是的。這是我的TreeView: BeginnerWpf 2011-03-24 23:09:33

回答

0

如果類如下所示:

public class FatherClass 
{ 
    public string Name { get; set; } 
    public List<ChildClass> Children { get; set; } 
} 

public class ChildClass 
{ 
    public string Name { get; set; } 
} 

,並在窗口,我有以下數據的構造函數:

 List<FatherClass> list = new List<FatherClass>(); 

     list.Add(new FatherClass { Name = "First Father" }); 
     list.Add(new FatherClass { Name = "Second Father" }); 

     list[0].Children = new List<ChildClass>(); 
     list[1].Children = new List<ChildClass>(); 

     list[0].Children.Add(new ChildClass { Name = "FirstChild" }); 
     list[0].Children.Add(new ChildClass { Name = "SecondChild" }); 
     list[1].Children.Add(new ChildClass { Name = "ThirdChild" }); 
     list[1].Children.Add(new ChildClass { Name = "ForthChild" }); 

     this.DataContext = list; 

然後以創建分層數據綁定,您應該在資源中定義兩個分層數據模板以「捕捉」相關數據類型,如下所示:

<Grid.Resources> 
     <HierarchicalDataTemplate DataType="{x:Type my:FatherClass}" ItemsSource="{Binding Children}" > 
      <TreeViewItem Header="{Binding Name}" /> 
     </HierarchicalDataTemplate> 
     <HierarchicalDataTemplate DataType="{x:Type my:ChildClass}" > 
      <TreeViewItem Header="{Binding Name}" /> 

     </HierarchicalDataTemplate> 
    </Grid.Resources> 

然後,樹形視圖的語法應爲:

<TreeView ItemsSource="{Binding }"> 

    </TreeView>