- Create a node class that implement IHierarchyData
- Create a control derived from HierarchicalDataSourceControl.
- Create a specialized collection to hold your nodes and implement IHierarchicalEnumerable
- Implement a HierarchicalDataSourceView
- Override the GetHierarchicalView method in the HierarchicalDataSourceControl.
The first four steps are easy. Create the classes and implement the methods, pretty straight foreward. Using generics the collection just requires an implementation for IHierarchicalEnumerable.GetHierarchyData which can be as simple as a type cast since the node class implements IHierarchyData. I'll get back to implementing the nodes later. Implementing the HierarchicalDataSourceView is not that difficult either. It's just a wrapper around your collection. Store a copy of your collection class and return it in the Select method. That's all.
Overriding the GetHierarchicalView method
This is the method that does the actual work in the HierarchicalDataSource. The role of the viewPath parameter is the key to making this work; use it like a query. If you're loading objects from a database like me, the viewpath should be the unique key to the object. In the implementation use the viewPath to decide what to do:
- If the viewPath is empty, use the root node of your hierarchy. If you want to include the root node in the hierarchy, return the root node itself. If you don't return it's children.
- If viewPath is not empty, fetch the node pointed to by the viewPath and return it's children. This is crucial! Do not return the node itself, return it's children because when a view is requested for a node, it means the node was already returned in a previous call. If you return the node itself, the datasource will get stuck in an endless loop...
Implementing the nodes
The node implementation is nothing spectacular. Just make sure that the Path property returns something that you can process as a viewPath in your GetHierarchicalView implementation. If you want to bind a TreeView to your HierarchicalDataSourceControl you can use the Type property to hint the icon for the node. For example, when your hierarchy contains files and folders consider returning the mime type of the file so you can display the appropriate icon in the tree. I've compiled a simple ready-to-run sample (VS 2005) that uses a TreeView control to render the files in a given folder on disk.