WPF Reflections

Jan 24 2008   9:43AM GMT

Recursive data template



Posted by: Mark Shurmer
WPF

Yes, believe it or not, it is possible to have a recursive data template.

I was recently writing a ListBox that showed a directory, but I wanted the ListBox to show nested ListBoxes for subdirectories.
It turned out to be very easy with WPF:

<DataTemplate DataType=”{x:Type si:DirectoryInfo}”>
<ListBox ItemsSource=”{Binding Path=., Converter={StaticResource fileConv}}” />
</DataTemplate>

Where fileConv is a static resource to a converter class that converts a FileInfo into a string, and si refers to System.IO.

You may be thinking where is the recursion? The magic is in the fact that when the DataTemplate encounters a DirectoryInfo it will invoke the DataTemplate for that DirectoryInfo, and suddenly it just all works.

Comment on this Post


You must be logged-in to post a comment. Log-in/Register