Click here to Skip to main content
Click here to Skip to main content

WPF TreeView tools

, 5 May 2009
Rate this:
Please Sign up or sign in to vote.
Additional helper methods for the WPF TreeView (especially with data binding).

Introduction

While working with the WPF TreeView and data binding, I ran into the problem that the TreeViewItems and my real objects were only loosely connected. That's why I decided to code some methods for the most important tasks like selecting, expanding, ... TreeViewItems that take my bound object as a parameter.

Using the Code

To use my small library, simply copy the file into your project. All the methods are implemented as extension methods for the TreeView or the TreeViewItem class.

The heart and soul of this library is the GetItemFromObject method:

/// <summary>
/// Returns the TreeViewItem of a data bound object.
/// </summary>
/// <param name="treeView">TreeView</param>
/// <param name="obj">Data bound object</param>
/// <returns>The TreeViewItem of the data bound object or null.</returns>
public static TreeViewItem GetItemFromObject(this TreeView treeView, object obj)
{
  try
  {
    DependencyObject dObject = GetContainerFormObject(treeView, obj);
    TreeViewItem tvi = dObject as TreeViewItem;
    while (tvi == null)
    {
      dObject = VisualTreeHelper.GetParent(dObject);
      tvi = dObject as TreeViewItem;
    }
    return tvi;
  }
  catch { }
  return null;
}

private static DependencyObject 
        GetContainerFormObject(ItemsControl item, object obj)
{
  DependencyObject dObject = null;
  dObject = item.ItemContainerGenerator.ContainerFromItem(obj);
  if (dObject == null)
  {
    if (item.Items.Count > 0)
    {
      foreach (object childItem in item.Items)
      {
        ItemsControl childControl = item.ItemContainerGenerator.
              ContainerFromItem(childItem)as ItemsControl;
        dObject = GetContainerFormObject(childControl, obj);
        if (dObject != null)
        {
          break;
        }
      }
    }
  }
  return dObject;
}

By this, you get the TreeViewItem container of your object. Unfortunately, this method works only if the TreeViewNode with the object is visible (all parent nodes must be expanded). The GetContainerFromObject method is an internal helper to walk the VisualTree to find your object in the deeper tree levels. The VisualTreeHelper is the main reason why all parent nodes must be expanded.

All the following methods use this method to get the TreeViewItem, and then set or read the TreeViewItem's property.

public static void SelectObject(this TreeView treeView, object obj)
public static void SelectObject(this TreeView treeView, object obj, bool selected) 
public static bool IsObjectSelected(this TreeView treeView, object obj)
public static bool IsObjectFocused(this TreeView treeView, object obj)
public static void ExpandObject(this TreeView treeView, object obj)
public static void ExpandObject(this TreeView treeView, object obj, bool expanded)
public static bool IsObjectExpanded(this TreeView treeView, object obj)

The last method simply returns the parent TreeViewItem of a given TreeViewItem (can anyone tell me why this is missing in WPF or am I just blind!)

public static TreeViewItem GetParentItem(this TreeViewItem item)

Points of Interest

The TreeView shows me both sides of WPF: you get a super simple data binding with hierarchy, automatic updates, and so on, but on the other side, such simple things like walking a TreeView, expanding/collapsing items get a bit complex if you use data binding because of the super flexible Visual and Logical tree architecture.

I will extend this library in the future and update it from time to time. Any suggestions are welcome.

History

  • 05-05-2009: Original version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Reinhard Ostermeier
Software Developer (Senior) remes GmbH
Germany Germany
No Biography provided

Comments and Discussions

 
QuestionWhat about collapsed tree? PinmemberSergey Zwezdin9-Nov-10 21:50 
AnswerRe: What about collapsed tree? PinmemberReinhard Ostermeier4-Dec-10 21:44 
You are right.
This is a known issue to me.
But in the way I use it, this does not happen really often to me.
I usually use it to add new items to the selected item or delete the selected item.
So if you add the new item, expand the parent item and select the new item then, it works.
 
Because the visual tree is only extended when it's needed, I can not think of a working solution to this problem so far (except some MVVM solution which would be way to complex for me in many situations).
 
Reinhard.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140827.1 | Last Updated 5 May 2009
Article Copyright 2009 by Reinhard Ostermeier
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid