在代码中添加项目时,使用ItemTemplate进行TreeView

时间:2009-07-23 23:24:34

标签: wpf xaml treeview datatemplate itemtemplate

我在后面的代码中手动添加TreeViewItems,并希望使用DataTemplate来显示它们,但无法弄清楚如何使用。我希望做这样的事情,但项目显示为空标题。我做错了什么?

XAML

<Window x:Class="TreeTest.WindowTree"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WindowTree" Height="300" Width="300">
    <Grid>
        <TreeView Name="_treeView">
            <TreeView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Path=Name}" />
                        <TextBlock Text="{Binding Path=Age}" />
                    </StackPanel>
                </DataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>
    </Grid>
</Window>

代码背后

using System.Windows;
using System.Windows.Controls;

namespace TreeTest
{
    public partial class WindowTree : Window
    {
        public WindowTree()
        {
            InitializeComponent();

            TreeViewItem itemBob = new TreeViewItem();
            itemBob.DataContext = new Person() { Name = "Bob", Age = 34 };

            TreeViewItem itemSally = new TreeViewItem();
            itemSally.DataContext = new Person() { Name = "Sally", Age = 28 }; ;

            TreeViewItem itemJoe = new TreeViewItem();
            itemJoe.DataContext = new Person() { Name = "Joe", Age = 15 }; ;
            itemSally.Items.Add(itemJoe);

            _treeView.Items.Add(itemBob);
            _treeView.Items.Add(itemSally);
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

2 个答案:

答案 0 :(得分:11)

您的ItemTemplate正在尝试在TextBlocks中呈现“Name”和“Age”属性,但TreeViewItem没有“Age”属性,并且您没有设置其“Name”。

因为你正在使用ItemTemplate,所以不需要将TreeViewItems添加到树中。而是直接添加您的Person实例:

_treeView.Items.Add(new Person { Name = "Sally", Age = 28});

问题当然是你的底层对象(“Person”)没有任何层次结构的概念,因此没有简单的方法将“Joe”添加到“Sally”。还有一些更复杂的选择:

您可以尝试处理TreeView.ItemContainerGenerator.StatusChanged事件并等待生成“Sally”项,然后获取它的句柄并直接添加Joe:

public Window1()
{
    InitializeComponent(); 
    var bob = new Person { Name = "Bob", Age = 34 }; 
    var sally = new Person { Name = "Sally", Age = 28 }; 

    _treeView.Items.Add(bob); 
    _treeView.Items.Add(sally);

    _treeView.ItemContainerGenerator.StatusChanged += (sender, e) =>
    {
        if (_treeView.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated) 
            return;

        var sallyItem = _treeView.ItemContainerGenerator.ContainerFromItem(sally) as TreeViewItem;
        sallyItem.Items.Add(new Person { Name = "Joe", Age = 15 });
    };
}

或者,更好的解决方案,您可以将层次结构概念引入“Person”对象,并使用HierarchicalDataTemplate定义TreeView层次结构:

XAML:

<Window x:Class="TreeTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WindowTree" Height="300" Width="300">
    <Grid>
        <TreeView Name="_treeView">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Subordinates}">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Path=Name}" />
                        <TextBlock Text="{Binding Path=Age}" />
                    </StackPanel>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>
    </Grid>
</Window>

CODE:

using System.Collections.Generic;
using System.Windows;

namespace TreeTest
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent(); 
            var bob = new Person { Name = "Bob", Age = 34 }; 
            var sally = new Person { Name = "Sally", Age = 28 }; 

            _treeView.Items.Add(bob); 
            _treeView.Items.Add(sally);
            sally.Subordinates.Add(new Person { Name = "Joe", Age = 15 });
        }

    }
    public class Person 
    {
        public Person()
        {
            Subordinates = new List<Person>();
        }

        public string Name { get; set; } 
        public int Age { get; set; }
        public List<Person> Subordinates { get; private set;  }
    }
}

这是一种更“面向数据”的方式来显示您的层次结构和更好的方法恕我直言。

答案 1 :(得分:0)

如果将DataTemplate从TreeView中拉出并将其放入Window.Resources,它将起作用。像这样:

<Window.Resources>    
    <DataTemplate DataType={x:type Person}>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Path=Name}" />
            <TextBlock Text="{Binding Path=Age}" />
        </StackPanel>
    </DataTemplate>
</Window.Resources>

不要忘记在Person之前添加正确的命名空间。