Friday, January 30, 2009

How to quickly wrap a single item into a collection

The situation

I just started to play with WPF and I like that very much. Its a lot easier to do many things that were very hard to do in Win Forms.

I’m working on a software that need a tree view. In win form you have to build the entire tree a node at a time, adding them recursively until done. In WPF though, there is a faster way to do that.

First let say we have a tree structure like this:

public class TreeNode
{
    private BindingList<TreeNode> _children;

    public BindingList<TreeNode> Children
    {
        get { return children; }
        set { /* setter code */ }
    }
}

Later in your code you define a property of that type to bind to:

public TreeNode Root
{
    get { return _root; }
}

With this code you can build a structured tree of nodes. Then you can use a TreeView object in your xaml file:

<TreeView Name="treeView1"
          ItemsSource="{Binding ElementName=Win,Path=Root}"
          ItemTemplate="{StaticResource NodeTemplate}" />

The Problem

The problem with this is that the TreeView needs a collection or at least an enumerable source as its ItemSource. What if we don’t want to bind to the Children property of the root? What if we have some interesting property to show on the root node?

The Solution

We can build a temporary collection to pleased the TreeView:

public List<TreeNode> Root
{
	get 
	{
		var list = new List<TreeNode>;
		list.Add(_root);
		return list;
	}
}

Of course this will work. But isn’t a little too much having to create an instance of a list object to do that? Here is a simpler an more efficient way to achieve the same result.

public IEnumerable<TreeNode> Root
{
	get { yield return _root; }
}

Wow! That’s short! If you don’t know what “yield return” keyword is, you may find this code sample a little odd. “yield return” is what LINQ uses internally to iterate thru any IEnumerable data source without having to build an internal list. In our case we only need a list of one item, so using this technique can optimise your code.

1 comment:

meh said...

YA..... You always do some funky coding there. You deserve A+ for Funking your code :P