2

我一直在尝试制作一个看起来像的树视图

2001(根)
-Student1(节点)
-Student2(节点)

我试过使用分层数据模板,但我仍然没有掌握我需要什么。这是我希望将树视图绑定到的代码。任何有关 Xaml 的帮助都会得到帮助。

我以为它看起来像

    <TreeView ItemsSource="{Binding CurrentClass}">
        <TreeView.Resources>
            <HierarchicalDataTemplate DataType="{x:Type local:Student}" ItemsSource="{Binding CurrentClass.Students}">
                    <TextBlock Text="{Binding CurrentClass.Students/FirstName}" />
                </HierarchicalDataTemplate>
        </TreeView.Resources>
    </TreeView>
public class ViewModel
{
    public FreshmenClass currentClass = new FreshmenClass();

    public ViewModel()
    {
        currentClass.Year = "2001";
        currentClass.Students.Add(new Student("Student1", "LastName1"));
        currentClass.Students.Add(new Student("Student2", "LastName2"));
    }

    public FreshmenClass CurrentClass
    {
        get { return currentClass; }
    }
}

public class FreshmenClass
{
    public string Year { get; set; }
    public List<Student> students = new List<Student>();

    public List<Student> Students
    {
        get { return students; }
        set { students = value; }
    }
}

public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Student(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}
4

1 回答 1

5

查看有关 Treeview 和 HierarchicalDataTemplate 的文档。无论如何,我像这样编辑您的示例(XAML):

<TreeView ItemsSource="{Binding CurrentClass}" >
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Students}">
                <TextBlock Text="{Binding Year}" />
                <HierarchicalDataTemplate.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding FirstName}"> </TextBlock>
                    </DataTemplate>
                </HierarchicalDataTemplate.ItemTemplate>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>

和 c#:

public class ViewModel 
{
    private List<FreshmenClass> currentClass;

    public ViewModel()
    {
        CurrentClass = new List<FreshmenClass>();
        FreshmenClass temp = new FreshmenClass();
        temp.Year = "2001";
        temp.Students.Add(new Student("Student1", "LastName1"));
        temp.Students.Add(new Student("Student2", "LastName2"));

        CurrentClass.Add(temp);
    }

    public List<FreshmenClass> CurrentClass
    {
        get { return currentClass; }
        set { currentClass = value; }
    }
}

ItemsSource 属性是一个 IEnumerable。

于 2012-09-27T08:55:33.667 回答