在 WPF 中构建树视图 [英] Build a treeview in WPF

查看:38
本文介绍了在 WPF 中构建树视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 WPF 中构建一个三级树视图.基本上,我有一个顶级项目列表,这些项目都有一个子项目.这些子项可能有也可能没有自己的子项.

I am trying to build a three level treeview in WPF. Basically, I have a list of top level items that all have one more child items. Those child item may or may not have themselves chid items.

有人知道网上有教程吗?

Anyone know of a tutorial available on the net?

推荐答案

最简单的方法是使用绑定和 HierarchicalDataTemplate.用你的数据声明一个类:

The simplest way is to use bindings and HierarchicalDataTemplate. Declare a class with your data :

class Item : INotifyPropertyChanged
{
    public Item()
    {
        this.Children = new ObservableCollection<Item>();
    }

    public event PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            OnPropertyChanged("Name");
        }
    }

    public ObservableCollection<Item> Children { get; private set; }
}

并为此类型定义一个 HierarchicalDataTemplate :

And define a HierarchicalDataTemplate for this type :

<HierarchicalDataTemplate DataType="{x:Type my:Item}"
                          ItemsSource="{Binding Items}">
    <TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>

现在您只需要将TreeViewItemsSource 绑定到您的顶级项目集合,树节点将自动构建.如果您需要添加(或删除)一个节点,只需将一个项目添加到(或从)父集合中删除

Now you just need to bind the ItemsSource of the TreeView to your collection of top-level items, and the tree nodes will be constructed automatically. If you need to add (or remove) a node, just add an item to (or remove it from) the parent collection

在这个例子中,我使用了单一的项目类型,但是如果你有多种类型要显示在 TreeView 中,你需要为每个类型定义一个 HierarchicalDataTemplate.对于叶节点(没有子节点的节点),您可以只使用常规的 DataTemplate

For this example, I used a single item type, but if you have several types to display in the TreeView you will need to define a HierarchicalDataTemplate for each. For leaf nodes (nodes with no children), you can just use a regular DataTemplate

这篇关于在 WPF 中构建树视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆