V
V
Vladislav Sofienko2017-03-27 22:46:31
WPF
Vladislav Sofienko, 2017-03-27 22:46:31

How to find out the level in the hierarchy of the selected item in TreeView?

For example, there is a tree list:

- Уровень 1
   - Уровень 2
   - Уровень 2
      - Уровень 3
- Уровень 1
   - Уровень 2
      - Уровень 3
      - Уровень 3
   - Уровень 2
- Уровень 1
   - Уровень 2

It doesn't matter what the data is, but how do I get the hierarchy level of the currently selected item in the tree list?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sumor, 2017-03-27
@Sumor

When you are programming in WPF, the visual part is meant to be a reflection of your presentation of the data. Therefore, the hierarchy level of the selected item should not be found among the TreeViewItem elements, but among the parents of the selected item in accordance with the data presentation model.
Example:

class A
{
 public string Name{get;set;}
 public A Parent {get;set;}
 public IEnumerable<A> Children
 {
  get
  {
    return AllItemsOfA.Select(a => a.Parent == this);
  }
 }
 public int Level()
 {
  int level = 0;
  var current = Parent;
  while(current != null)
  {
    current = current.Parent;
    level ++;
  }
  return level;
 }
}

By adding a collection of such elements to the TreeView, you will get the hierarchy level you need for the selected element.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question