在WPF TreeView中递归绑定

时间:2010-08-18 15:45:20

标签: wpf data-binding treeview

我试图以递归方式绑定到TreeView中项目的子项。从我在MSDN上看到的HierarchicalDataTemplate是可行的方法,但到目前为止我只是部分成功。

我的课程:

 public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DocumentText test = new DocumentText();
        this.DataContext = test;

        for (int i = 1; i < 5; i++)
        {
            test.AddChild();
        }
        foreach (DocumentText t in test.Children)
        {
            t.AddChild();
            t.AddChild();
        }
    }
}

partial class DocumentText
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public override string ToString()
    {
        return Name;
    }

    public List<DocumentText> _children;
    public List<DocumentText> Children
    {
        get { return this._children; }
    }

    public DocumentText()
    {
        _name = "Test";
        _children = new List<DocumentText>();
    }

    public void AddChild()
    {
        _children.Add(new DocumentText());
    }
}

我的XAML:   在mainview.xaml中:

    <Window x:Class="treetest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TreeView Name="binderPanel" DockPanel.Dock="Left" 
                      MinWidth="150" MaxWidth="250" Background="LightGray"
                      ItemsSource="{Binding Children}">
        </TreeView>
    </Grid>
</Window>

在app.xaml:

    <HierarchicalDataTemplate x:Key="BinderTemplate"
 DataType="{x:Type src:DocumentText}" ItemsSource="{Binding Path=/Children}">
            <TreeViewItem Header="{Binding}"/>
        </HierarchicalDataTemplate>

此代码生成第一个子项的列表,但不显示嵌套子项。

1 个答案:

答案 0 :(得分:4)

您发布的主要问题是您没有将HierarchicalDataTemplate连接为TreeView的ItemTemplate。您需要设置ItemTemplate="{StaticResource BinderTemplate}"或删除x:Key以将模板应用于所有DocumentText实例。您还应该将模板中的TreeViewItem更改为TextBlock - 为您生成TreeViewItem,并将您放在该模板中的内容作为HeaderTemplate应用于它。