Alan
Alan

Reputation: 2086

Specifying additional data elements for TreeViewItem?

I have a TreeView that has multiple levels. I would like to assign the top level items as "Parent" items so that when they are clicked on I can see that set property and change which tab is selected in a TabControl.

So far the only useful thing I can see to set without screwing things up is the Uid, is there any way to add extra properties to the TreeViewItems? I am thinking of when I worked in Javascript and CSS and how you could add extra data tags to any element and wasn't sure if you can do that in C#

var serverGroupList = ServerDB.ExecuteDB("SELECT * FROM server_groups");
var json = JsonConvert.SerializeObject(serverGroupList);
dynamic dynJson = JsonConvert.DeserializeObject(json);

foreach (var item in dynJson)
{
    Console.WriteLine("Adding ServerGroup: " + item.name);
    ComboboxItem DropdownItem = new ComboboxItem();
    DropdownItem.Text = item.name.ToString();
    DropdownItem.Value = item.id;

    ServerGroupDropdown.Items.Add(DropdownItem);

    treeItem = new TreeViewItem();
    treeItem.Header = item.name;
    treeItem.Uid = item.id;
    var serverListResults = ServerDB.ExecuteDB("SELECT * FROM servers WHERE group_id = " + item.id);
    var serversJSON = JsonConvert.SerializeObject(serverListResults);
    dynamic servers = JsonConvert.DeserializeObject(serversJSON);
    foreach (var server in servers)
    {
        Console.WriteLine("Adding: " + server.name);
        treeItem.Items.Add(new TreeViewItem() { Header = server.name, Uid = server.id });
    }
    ServerList.Items.Add(treeItem);
}

Upvotes: 1

Views: 381

Answers (1)

ASh
ASh

Reputation: 35693

wpf TreeView can do much more than just show text Header of each item. Please study this CodeProject article to get the overview: Basic Understanding of Tree View in WPF. When using bindings and templates it becomes unnecessary to create TreeViewItems in code behind (All necessary properties are stored in the data items. TreeView generates TreeViewItems automatically for each data item, and there is 1:1 relation between data item and TreeViewItem.DataContext)

Still, to continue with your current approach, store any additional data in DataContext property:

treeItem = new TreeViewItem();
treeItem.Header = item.name;
treeItem.Uid = item.id;
treeItem.DataContext = item;

and

treeItem.Items.Add(new TreeViewItem { Header = server.name, Uid = server.id, DataContext = server });

Upvotes: 2

Related Questions