Recursive Command


Note: this entry has moved.</p>

When building up a tree view that represents the directory structure of a file system, like the windows explorer, my first reaction was to use recursion to traverse the file system and build up a tree. I quickly found that doing something like that is a time consuming process, and required some optimization.

I came up with what I like to call the recursive command. Each Tree Node item on a tree view is bound to a command to execute. The command looks like this…

public interface ITreeNodeClickedCommand {
    void Execute(ITreeNode node);

When the command is executed, the command gets an opportunity to modify the state of the tree node that was clicked. In this case I wanted to lazy load the sub directories of a node that was clicked. The command implementation looks like this…

public interface IAddFoldersCommand : ITreeNodeClickedCommand {}

public class AddFoldersCommand : IAddFoldersCommand {
    private readonly DirectoryInfo the_current_directory;
    private bool has_executed;

    public AddFoldersCommand(DirectoryInfo the_current_directory) {
        this.the_current_directory = the_current_directory;

    public void Execute(ITreeNode node) {
        if (!has_executed) {
            foreach (var directory in the_current_directory.GetDirectories()) {
                node.Add(new TreeNodeItem(directory.Name, ApplicationIcons.Folder, new AddFoldersCommand(directory)));
        has_executed = true;

This command is executed each time the tree node that it is bound too is clicked, but will only build up the child tree node items once. Each of the child tree nodes are bound to a new instance of the same command. Hence, what I like to call the recursive command.



For more information on the command pattern check out WikiPedia’s write up.

Trust & Transparency