views:

1311

answers:

1

After you have added Items to the "root" level of a System.Windows.Controls.TreeView, what is the proper way to add in "subitems" by name?

System.Windows.Controls.TreeView.Items <-- doesn't seem to have a Find() or [] by name.

UPDATE: Oh, wait... is it TreeView.FindName() ?

Actually looks like FindName won't work because it returns an object, not something you can add subitems too.

On a second note: Is it wrong to use a class like this to load it up with items, since it doesn't provide a TreeNode like WinForms?

public class TreeItem
{
    public string Name { get; set; }
    public string Text { get; set; }
    public object Tag { get; set; }
}
+1  A: 

You can use .Where ExtensionMethod on the TreeView.Items collection, and then find by whatever you want.

There isn't a TreeNode any more in WPF, instead a TreeView has TreeViewItems, ListView has ListViewItems, etc. So the TreeViewItem is what you should be using in these case. (Though you can add anything you like to the TreeView, it'll wrap it for you.)

FindName returns an object because it doesn't know what it's going to find, you have to cast it to what you expect it to be. But that is the behavior you want to be using. Also, while any elements with a Name are automatically registered if they are created in XAML, that is not the case if you are creating the items in C#/VB and adding them to the UI. You will have to 'register' their name in order to be able to access it by FindName().

Here's a small example demonstrating the TreeViewItem and accessing TreeView's elements through FindName:

TreeView tree = new TreeView() { Name = "tree" };
uiDockPanel.Children.Add(tree);

var item1 = new TreeViewItem() { Header = "Item 1", Name = "Item1" };
tree.Items.Add(item1); 
item1.RegisterName("Item1", item1);

var item2 = new TreeViewItem() { Header = "Item 2", Name = "Item2" };
tree.Items.Add(item2); 
item1.RegisterName("Item2", item2);

var item3 = new TreeViewItem() { Header = "Item 3", Name = "Item3" ;
tree.Items.Add(item3);    
item1.RegisterName("Item3", item3);

var i2 = tree.FindName("Item2") as TreeViewItem;
var subitem = new TreeViewItem() { Header = "SubItem 1"};
i2.Items.Add(subitem);
rmoore