totallhellfail
totallhellfail

Reputation: 70

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.

Upvotes: 0

Views: 3411

Answers (1)

CodeWarrior
CodeWarrior

Reputation: 7468

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.

Upvotes: 1

Related Questions