Wpf Xaml - TreeView分层数据模板 - 多个项目源

时间:2011-03-24 22:43:56

标签: wpf treeview controls

我有一个这样的类(描述C#中的类及其字段,方法等):

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;
        }
    }

每个Field,Method,Property都有一个“Name”属性 我想要TreeView(例如):

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

xaml看起来怎么样?谢谢你的帮助

1 个答案:

答案 0 :(得分:0)

如果课程如下:

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

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

在窗口的ctor中我有以下数据:

        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>