Pages

Friday, January 20, 2012

Working with WPF TreeView Control

With C#, I recursively populated a WPF TreeView control. TreeView control will be populated with a directory listing with their respective files. The code is below:
On Page Load:

XAML:

<TreeView Name="Dir" Height="310">
</TreeView>

Initialize a recursive function call: treeViewItem(DirectoryInfo):

DirectoryInfo dir = new DirectoryInfo(@"C:\Kirk\Images");
Dir.Items.Add(treeViewItem(dir));

Recursive function:
private TreeViewItem treeViewItem(DirectoryInfo dir)
 {
     TreeViewItem tvi = new TreeViewItem();
     tvi.Header = dir.Name;
 
     foreach (DirectoryInfo dirInfo in dir.GetDirectories())
     {
         TreeViewItem t = treeViewItem(dirInfo);
         tvi.Items.Add(t);
     }
 
     IEnumerable<TextBlock> textBlock = dir.GetFiles().Select(f => new TextBlock {Text = f.Name} );
 
     foreach (TextBlock tb in textBlock)
     {
         tvi.Items.Add(tb);
     }
 
     return tvi;
 }

I use lambda expressions on any collection. Lambda expressions are extremely productive and tight.

My coding information.

No comments:

Post a Comment