如何在TreeListView中绑定数据

时间:2018-08-27 10:54:08

标签: c# wpf

我使用以下文章中的TreeListView:https://blogs.msdn.microsoft.com/atc_avalon_team/2006/03/01/treelistview-show-hierarchy-data-with-details-in-columns/

我不知道如何在XAML之外设置属性。 假设我有一个具有lastNamefirstNamegenderage属性的人员类别,每个人都应将其子级作为嵌套级别。我该如何实现?

1 个答案:

答案 0 :(得分:2)

型号:

public class Person
{
    public Person(string name)
    {
        this.Name = name;
    }

    public string Name { get; set; }

    public ObservableCollection<Person> Childs { get; set; }
}

XAML:

<TreeView ItemsSource="{Binding Path=Persons}">
    <TreeView.Resources>               
        <HierarchicalDataTemplate DataType="{x:Type local:Person}" ItemsSource="{Binding Childs}">
            <TextBlock Text="{Binding Name}"/>
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>

MainWindow:

public partial class MainWindow : Window
{
    public MainWindow()
    {


        Persons = new ObservableCollection<Person>();
        Persons.Add(new Person("Name1"));
        Persons[0].Childs = new ObservableCollection<Person>();
        Persons[0].Childs.Add(new Person("Child1"));
        Persons[0].Childs.Add(new Person("Child2"));
        Persons[0].Childs[0].Childs = new ObservableCollection<Person>();
        Persons[0].Childs[0].Childs.Add(new Person("Child1 Child2"));



        InitializeComponent();

        this.DataContext = this;
    }

    public ObservableCollection<Person> Persons { get; private set; }
}

希望有帮助。