简体   繁体   English

将类绑定到WPF树视图

[英]Binding a class to a WPF Treeview

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>();
    }
}

Thanks in advance. 提前致谢。

The easiest way to do it is with HierarchicalDataTemplates. 最简单的方法是使用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. 另外,添加一个指向下一层的ItemsSource属性。

<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. 设置数据模板的样式以适合您的口味。

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 . 如果您当前正在使用MVVM(或者打算开始使用它),请查看下面的链接,以获得有关将树视图与MVVM一起使用的非常好的文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM