Custom WPF TreeView
- by Robert
I have a custom class that I would like to bind a WPF TreeView that has three tiers. Each tier needs to be bound like this:
Monitor
--> LCD
--> Samsung 1445 LCD
--> CRT
--> Sony 125 CRT
Here is the example code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
SystemInventory sysInventory = new SystemInventory();
//Possibly do something like this.
_myTreeView.DataContext = sysInventory.DeviceGroupInstances;
}
public class SystemInventory
{
public ObservableCollection<DeviceGroup> DeviceGroupInstances { get; set; }
public SystemInventory()
{
DeviceGroupInstances = new ObservableCollection<DeviceGroup>();
DeviceGroupInstances.Add(new DeviceGroup("Monitor"));
}
}
public class DeviceGroup
{
public string DeviceGroupName { get; set; }
public ObservableCollection<DeviceType> DeviceTypeInstances { get; set; }
public DeviceGroup(string deviceGroupName)
{
DeviceTypeInstances = new ObservableCollection<DeviceType>();
DeviceGroupName = deviceGroupName;
if (deviceGroupName == "Monitor")
{
DeviceTypeInstances.Add(new DeviceType("LCD"));
DeviceTypeInstances.Add(new DeviceType("CRT"));
}
}
}
public class DeviceType
{
public string DeviceTypeName { get; set; }
public ObservableCollection<DeviceInstance> DeviceInstances { get; set; }
public DeviceType(string deviceGroupName)
{
DeviceInstances = new ObservableCollection<DeviceInstance>();
DeviceTypeName = deviceGroupName;
if (deviceGroupName == "Monitor")
{
DeviceInstances.Add(new DeviceInstance("Samsung 1445 LCD"));
}
else
{
DeviceInstances.Add(new DeviceInstance("Sony 125 CRT"));
}
}
}
public class DeviceInstance
{
public string DeviceInstanceName { get; set; }
public DeviceInstance(string instanceName)
{
DeviceInstanceName = instanceName;
}
}
}