Search code examples
c#wpftreeviewitem

How to get selected TreeViewItem items header?


I'm populating two-level TreeView from Dictonary<int, string> myFirstDictionary (for first level) and from Dictionary<string, int> mySecondDictionary (for 2nd level):

XAML:

<TreeView Name="myTreeView"/>

Code-behind:

TreeViewItem item;

foreach (var dict1 in myFirstDictionary)
{
     item = TreeViewItem();
     item.Header = dict1.Value;
     foreach (var dict2 in mySecondDictionary)
         if (dict1.Key == dict2.Value)
             item.Items.Add(dict2.Key);
     myTreeView.Items.Add(item);
}

This works just fine. I can easily get TreeViewItem's Header of first level using this code:

TreeVeiwItem tvi = myTreeView.SelectedItem as TreeViewItem;
MessageBox.Show(tvi.Header.ToString());

The problem is I don't know how to get second level TreeViewItem's Header (the one which is populated from dict2.Key.


Solution

  • Try this way:

    TreeViewItem tvItem = null;
    tvItem = ContainGenerator.ContainerFromItem(myTreeView.SelectedItem) as TreeViewItem;
    
    MessageBox.Show(tvItem.Header);