I would like to know how to bind a custom data type to a TreeView.
The data type is basically an arraylist of objects that contain other arraylists. Access would look something like this:
foreach (DeviceGroup dg in system.deviceGroups)
{
foreach (DeviceType dt in dg.deviceTypes)
{
foreach (DeviceInstance di in dt.deviceInstances)
{
}
}
}
I would like the TreeView to look something like this:
DeviceGroup1
--> DeviceType1
--DeviceInstance1
--DeviceInstance2
--> DeviceType2
--DeviceInstance1
DeviceGroup2
--> DeviceType1
--DeviceInstance1
--> DeviceType2
Ok this is where the
HierarchicalDataTemplatewill save you. The trick is you will need to use two different hierarchical templates, since you have a three-level hierarchy here. I have constructed a simpleUserControlto illustrate. First, here is some code-behind creating model data similar to what you have:Nothing difficult here, but note that you should use
ObservableCollectioninstead ofArrayListif you want to add and remove from your collections dynamically. Now let’s look at the XAML for this control:And here is the result:
alt text http://img684.imageshack.us/img684/6281/threeleveltreeview.png