Post navigation

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:

C#

1

2

3

4

5

6

7

8

9

10

publicclassTreeNode

{

privateBindingList&amp;lt;TreeNode&amp;gt;_children;

publicBindingList&amp;lt;TreeNode&amp;gt;Children

{

get{returnchildren;}

set{/* setter code */}

}

}

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

C#

1

2

3

4

publicTreeNodeRoot

{

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:

C#

1

2

3

&lt;TreeView Name=&quot;treeView1&quot;

ItemsSource=&quot;{Binding ElementName=Win,Path=Root}&quot;

ItemTemplate=&quot;{StaticResource NodeTemplate}&quot;/&gt;

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:

C#

1

2

3

4

5

6

7

8

9

publicList&lt;TreeNode&gt;Root

{

get

{

varlist=newList&lt;TreeNode&gt;;

list.Add(_root);

returnlist;

}

}

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.

C#

1

2

3

4

publicIEnumerable&lt;TreeNode&gt;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.