将类绑定到 WPF 树视图 [英] Binding a class to a WPF Treeview

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

问题描述

我有一个对象,它包含一个可观察的集合我正在努力思考如何将这一切都粘贴到树状视图中.所以主要对象将是父对象,可观察集合中的项目是子子对象.目前该类具有可以绑定到标头的公共字符串属性.以下是课程的部分内容:

I have an object, which holds an observable collection Im trying to wrap my head around how to stick this all into a treeview. So the main object would be a parent and items in observable collection are sub-children. Currently the class has public string property which could be bound to a header. Here are parts of the class:

public class ServerObject : INotifyPropertyChanged
{
    private string _serverName;
    ObservableCollection<string> _instanceList;

    public ObservableCollection<string> InstanceList
    {
        get { return _instanceList; }
    }

    public string ServerName
    {
        get { return _serverName; }
        set
        {
            _serverName = value;
            RaisePropertyChanged("ServerName");
        }
    }

    public ServerObject(string name, string version)
    {

        ServerName = name;
        _instanceList = new ObservableCollection<string>();
    }
}

提前致谢.

推荐答案

最简单的方法是使用 HierarchicalDataTemplates.定义两个或更多模板.在模板声明行中为您的对象添加一个类型指示符.此外,添加一个指向下一层的 ItemsSource 属性.

The easiest way to do it is with HierarchicalDataTemplates. Define two or more templates. In the template declaration line add a type indicator for your object. Also, add an ItemsSource attribute which points to the next level down.

<HierarchicalDataTemplate Datatype="{x:Type local:mySerberObject}" ItemsSource="{Binding InstanceList}"/>

将顶级集合绑定到树视图,您应该可以正常运行了.根据您的喜好设置数据模板的样式.

Bind the top level collection to the treeview, and you should be off and running. Style the datatemplates to suit your taste.

如果您目前正在使用 MVVM(或者您打算开始使用它),请查看下面的链接,获取关于 在 MVVM 中使用树视图.

If you are currently using MVVM (or if you plan to start using it) check out the link below for a really good article about using the treeview with MVVM.

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

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