Binding a class to a WPF Treeview

2019-08-28 21:05发布

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.

标签: c# wpf treeview
1条回答
冷血范
2楼-- · 2019-08-28 21:44

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.

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.

查看更多
登录 后发表回答