Friday, May 27, 2011

Programmatically selecting items in WPF Treeview

[Beginner level]


Hi All,


Today I am going to talk about a common problem of programmatically selecting items in the WPF Treeview. This problem is discussed in many forums but I want to present two contradicting approaches with a full explanations so that you can decide what is best.


I consider the following (somewhat common) case: I have some data represented as a tree. I decide to show my data in the UI inside a WPF Treeview and some general list of items (with no specific structure). When the user selects an item in the list the same item is selected in the tree. A good example is the Solution Explorer in your Visual Studio. You select a tab with your code and the relevant file is selected in the Solution Explorer tree.


For simplicity my data items look like this:

  public class DataItem
  {
    private static int _counter;
    public DataItem()
    {
      Name = string.Format("Item {0}"Interlocked.Increment(ref _counter));
      SubItems = new List<DataItem>();
    }
    public string Name
    {
      get;
      set;
    }
 
    public DataItem Parent
    {
      get;
      set;
    }
 
    public List<DataItem> SubItems
    {
      get;
      set;
    }
  }
An item has a unique name property which looks like "Item N" generated in the constructor. This is not important and done only to distinguish the various items.

My window contains a Treeview which looks like this:
        <TreeView x:Name="_mainTree" ItemsSource="{Binding Root}" >
            <TreeView.Resources>
                
                <HierarchicalDataTemplate DataType="{x:Type local:DataItem}" ItemsSource="{Binding SubItems}" >
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Name}" Margin="2,0,0,0" VerticalAlignment="Center" x:Name="TextArea" >
                        </TextBlock>
                    </StackPanel>
                </HierarchicalDataTemplate>
            </TreeView.Resources>
        </TreeView>

In the main window code I have the following:
 public partial class MainWindow : Window
  {
 
    private const int MaxLevel = 3;
    private const int ItemsPerLevel = 100;
 
    public MainWindow()
    {
      InitializeComponent();
      DataContext = this;
      Root = new ObservableCollection<DataItem>();
      DataItem rootItem = new DataItem();
      rootItem.IsSelected = true;
      AddSubItems(rootItem, 1);
      
      Root.Add(rootItem);
    }
 
    public ObservableCollection<DataItem> Root
    {
      get;
      set;
    }
 
    private void AddSubItems(DataItem node, int level)
    {
      if (level == MaxLevel)
        return;
      for (int i = 0; i < ItemsPerLevel; i++)
      {
        DataItem subitem = new DataItem();
        AddSubItems(subitem,level+1);
        subitem.Parent = node;
        node.SubItems.Add(subitem);
      }
    }

(I assume you have some experience with WPF and binding so you understand why this code would populate the tree)
The method AddSubitems generates some levels of tree items (2 in the above code) each containing 
ItemsPerLevel (100) items.

This is where the two approaches split...

The "I don't care about data/UI separation" approach
Since I don't care about data and UI separation I will simply add two properties to my DataItem:
IsSelected to mark when an item is selected and IsExpanded because when an internal item is selected I would like to see it.
The DataItem code now looks like this:
  public class DataItem:INotifyPropertyChanged
  {
    private static int _counter;
    public string Name
    {
      get;
      set;
    }
 
    private bool _isSelected;
    public bool IsSelected
    {
      get
      {
        return _isSelected;
      }
      set
      {
        _isSelected = value;
        OnPropertyChanged("IsSelected");
      }
    }
 
    private bool _isExpanded;
    public bool IsExpanded
    {
      get
      {
        return _isExpanded;
      }
      set
      {
        _isExpanded = value;
        OnPropertyChanged("IsExpanded");
      }
    }
 
    public DataItem Parent
    {
      get;
      set;
    }
 
    public DataItem()
    {
      Name = string.Format("Item {0}"Interlocked.Increment(ref _counter));
      SubItems = new List<DataItem>();
    }
 
    public List<DataItem> SubItems
    {
      get;
      set;
    }
 
    private void OnPropertyChanged(string name)
    {
      if (PropertyChanged != null)
        PropertyChanged(thisnew PropertyChangedEventArgs(name));
    }
    public event PropertyChangedEventHandler PropertyChanged;
  }
One additional change you might notice is the introduction of the INotifyPropertyChanged interface which will help me to update the UI elements using binding.

Now all that remains is to hook the new properties to the Treeview and we have our solution.
I add the following style declaration to the resources tag of the tree:
 <Style TargetType="{x:Type TreeViewItem}">
     <Setter Property="IsSelected"  Value="{Binding IsSelected, Mode=TwoWay}"/>
     <Setter Property="IsExpanded"  Value="{Binding IsExpanded, Mode=TwoWay}"/>
 </Style>

Thats it, we are ready. I run the code:
      Root[0].SubItems[0].SubItems[0].IsSelected = true;
And the root element is being selected. Hmm... Something went wrong. I clearly did not select the root element! Checking the debugger reveals that the IsSelected property on the root element is indeed "true" but on the the DataItem Root[0].SubItems[0].SubItems[0] it is also "true". 
The Treeview allows only one selected item so I have a problem here. 

The problem is quite simple. The WPF Treeview was designed to save time and memory consumption (Yei!) so it doesn't generate the tree items for the tree items you cannot see. So when you select a tree item which is not visible and was not previously created it does the next best thing and selecting the closest item in the hierarchy which is visible.
To solve this issue I change the IsExpanded property to look like:
    private bool _isExpanded;
    public bool IsExpanded
    {
      get
      {
        return _isExpanded;
      }
      set
      {
        _isExpanded = value;
        if (_isExpanded && Parent != null)
          Parent.IsExpanded = true;
        OnPropertyChanged("IsExpanded");
      }
    }
Now all I need to do is to expand the tree item so it will be seen. This for example can be done by calling:
      Root[0].SubItems[0].SubItems[0].IsSelected = true;
      Root[0].SubItems[0].SubItems[0].IsExpanded = true;
The "I don't mix my UI with my Data" approach
I return to the original code. I don't want to edit the data item so I would have to handle the selection manually. For this I introduce the SelectItem method in the main window that looks like this:

    private void SelectItem(DataItem node)
    {
      Stack<DataItem> nodesStack = new Stack<DataItem>();
      DataItem currentNode = node;
 
      while (currentNode != null)
      {
        nodesStack.Push(currentNode);
        currentNode = currentNode.Parent;
      }
 
      TreeViewItem currentItem = _mainTree.ItemContainerGenerator.ContainerFromItem(_mainTree.Items[0]) as TreeViewItem;
      currentNode = nodesStack.Pop();
 
      if (currentItem.Header != currentNode)
        return;
 
      while (nodesStack.Count > 0)
      {
        if (currentItem.IsExpanded == false)
        {
          currentItem.IsExpanded = true;
          currentItem.UpdateLayout();
        }
 
        currentNode = nodesStack.Pop();
        foreach (DataItem innerItem in currentItem.Items)
        {
          if (innerItem == currentNode)
          {
            currentItem = currentItem.ItemContainerGenerator.ContainerFromItem(innerItem) as TreeViewItem;
            break;
          }
        }
 
      }
 
      currentItem.IsSelected = true;
    }
What I am doing here is quite simple. WPF lets me get the TreeViewItem that holds my DataItem by using the ItemContainerGenerator. But, if you read the previous section you know that the containers are generated only once you see them so I am forced to start at the root and manually expand each tree level until I reach the required tree item. One thing to notice is that it isn't enough to set IsExpanded to true on a tree item. To build the container you must instruct WPF to update the layout and build the containers. Another thing to notice is that ItemContainerGenerator searches only within the current level of the tree so you must search each level separately.

I run test the code using the following line:
SelectItem(Root[0].SubItems[0].SubItems[0]);
And everything works great.

But.... (and I am ignoring the fact that you have lot's of calls to update layout, this can be optimized)

There is a problem. It is not immediately visible but try to increase the number of generated elements to 10000 and the number of levels to only 1.
    private const int MaxLevel = 2;
    private const int ItemsPerLevel = 10000;
I run the application and expand the root tree item and wait. And wait... Still waiting... I waited about 10 seconds for the tree item to expand because it has so many containers to generate. Thankfully the WPF engineers thought about this issue and enabled Virtualization on the tree. To make long story short it means that you can tell WPF not to generate containers for tree items which are not actually visible to the user. I do so by adding the following attribute to my Treeview element in the XAML:
VirtualizingStackPanel.IsVirtualizing="True"

Run the application, expand the root tree item and it takes less than 1 second. Thank you WPF engineers. Only one problem. My selection method assumes that every expanded tree item creates ALL of the container inside it. And surly enough trying to select a tree item which is not in the visible area results in an exception.

Conclusion
I presented two methods to programatically select an item within the tree. I want to note that in both methods the SelectedItem property of the tree is updated correctly. Which method you may use is both a philosophical and a design question. Perhaps you have a third, better method for this case. Please share it with me and my readers using the comments.

Thank you for reading,
Boris.