天天看點

WPF使用HierarchicalDataTemplate綁定Dictionary生成TreeView

原文:

WPF使用HierarchicalDataTemplate綁定Dictionary生成TreeView

Dictionary<string, CustomeType>中的CustomeType是一個集合,将其綁定生成一棵樹,樹的第一層節點是Dictionary的Key,第二層是CustomeType集合,所有代碼用XAML實作。

代碼如下:

<TreeView Name="dictree" ItemsSource="{Binding}">

    <TreeView.Resources>

        <HierarchicalDataTemplate ItemsSource="{Binding Value}" DataType="{x:Type local:Job}">

            <TextBlock Text="{Binding Id}"><TextBlock Text="{Binding Name}"></TextBlock></TextBlock>

        </HierarchicalDataTemplate>

    </TreeView.Resources>

    <TreeView.ItemTemplate>

        <HierarchicalDataTemplate ItemsSource="{Binding Value}">

            <TextBlock Text="{Binding Key}"></TextBlock>

            <HierarchicalDataTemplate.ItemTemplate>

                <DataTemplate>

                    <TextBlock Text="{Binding Name}"></TextBlock>

                </DataTemplate>

            </HierarchicalDataTemplate.ItemTemplate>

    </TreeView.ItemTemplate>

</TreeView>

Jobs jobs1 = new Jobs();

jobs1.Add(new Job() { Id = 1, Name = "CEO1"});

jobs1.Add(new Job() { Id = 2, Name = "CEO2"});

jobs1.Add(new Job() { Id = 3, Name = "CEO3"});

Jobs jobs2 = new Jobs();

jobs2.Add(new Job() { Id = 1, Name = "CEO1"});

jobs2.Add(new Job() { Id = 2, Name = "CEO2"});

jobs2.Add(new Job() { Id = 3, Name = "CEO3"});

Dictionary<string, Jobs> allJob = new Dictionary<string, Jobs>();

allJob.Add("CEO one", jobs1);

allJob.Add("CEO two", jobs2);

dictree.DataContext = allJob;

public class Job

{

    public int Id

    { get; set; }

    public string Name

    public string Status

}

public class Jobs : System.Collections.ObjectModel.ObservableCollection<Job> { }