Search code examples
c#wpftreeviewitemcollection

How to access elements from an ItemCollection?


I want to access the contents of an ItemCollection that contains the items from a Treeview (called OOB).

if (OOB.Items.Count > 0)
{
    ItemCollection items = OOB.Items;
    foreach (TreeViewItem node in items)

The foreach throws the runtime error:

Unable to cast object of type 'System.Xml.XmlElement' to type 'System.Windows.Controls.TreeViewItem'.

I can SEE the information in the ItemCollection items that I want to access from the debugger:

enter image description here

How can I access the elements, specifically the Element Name?


Solution

  • The Items or ItemsSource collection of an ItemsControl contains data items of an arbitrary type, not TreeViewItems (unless you explicitly add them).

    The Items collection of your TreeView contains XmlElements, which you can directly access like this:

    foreach (XmlElement node in OOB.Items)
    {
        var name = node.Name; // node is an XmlElement
        ...
    }
    

    In case you really need access to the item container, you may use the ItemsControl's ItemContainerGenerator like this:

    var treeViewItem = (TreeViewItem)OOB.ItemContainerGenerator.ContainerFromItem(node);