Click here to Skip to main content
15,867,308 members
Articles / Desktop Programming / WPF

WPF TreeView tools

Rate me:
Please Sign up or sign in to vote.
4.50/5 (3 votes)
5 May 2009CPOL1 min read 56.6K   1.7K   23   9
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:

C#
/// <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.

C#
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!)

C#
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)


Written By
Software Developer (Senior) remes GmbH
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionThank you Pin
Member 883438716-Aug-12 6:34
Member 883438716-Aug-12 6:34 
QuestionWhat about collapsed tree? Pin
Sergey Zwezdin9-Nov-10 21:50
Sergey Zwezdin9-Nov-10 21:50 
AnswerRe: What about collapsed tree? Pin
Reinhard Ostermeier4-Dec-10 21:44
Reinhard 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.
GeneralThanks! Pin
timtos27-Jun-09 14:13
timtos27-Jun-09 14:13 
GeneralRe: Thanks! Pin
timtos27-Jun-09 14:16
timtos27-Jun-09 14:16 
QuestionIs accessing UI items from code really good? Pin
FantasticFiasco14-May-09 20:12
FantasticFiasco14-May-09 20:12 
GeneralPlease add a screenshot Pin
Member 189546112-May-09 3:30
Member 189546112-May-09 3:30 
Rantthanks dude [modified] Pin
sachinblore5-May-09 17:49
sachinblore5-May-09 17:49 
QuestionRe: thanks dude Pin
Reinhard Ostermeier6-May-09 3:41
Reinhard Ostermeier6-May-09 3:41 

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

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