views:

20

answers:

2

I have the following 2 classes:

public class DeviceGroup
    {
        public String Name { get; set; }
        public ObservableCollection<DeviceGroup> DeviceGroups { get; set; }
        public ObservableCollection<Device> Devices { get; set; }


        public DeviceGroup()
        {
            Name = String.Empty;
            DeviceGroups = new ObservableCollection<DeviceGroup>();
            Devices = new ObservableCollection<Device>();
        }
    }

    public class Device
    {
        public String Name { get; set; }
    }

My main class has an ObservableCollection.

In my Xaml - I can create a treeview easily if I just specify DeviceGroup within my HierachicalDataTemplate, as follows:

<Window.Resources>
    <ResourceDictionary>
        <DataTemplate DataType="{x:Type local:Device}">
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>

        <HierarchicalDataTemplate DataType="{x:Type local:DeviceGroup}" ItemsSource="{Binding DeviceGroups}">
            <StackPanel>
                <TextBlock Text="{Binding Name}"/>
            </StackPanel>
        </HierarchicalDataTemplate>
    </ResourceDictionary>
</Window.Resources>
<Grid>        
    <TreeView ItemsSource="{Binding DeviceGroups}"/>
</Grid>

The question is: How can I select the Devices collection as well as the DeviceGroup? I'd like the Devices to appear something like Windows Explorer (Directories and Files). Is there a Xaml solution to this problem? Or will I have to create the TreeViewItems in the codebehind. Thanks.

A: 

The only solution I've found so far is within the code behind:

    private void LoadTree()
    {
        foreach (DeviceGroup dg in ttvm.DeviceGroups)
        {
            TreeViewItem tvi = new TreeViewItem();
            tvi.Header = dg;
            treeView1.Items.Add(tvi);
            AddTreeItems(tvi, dg);
        }
    }

    private void AddTreeItems(TreeViewItem node, DeviceGroup deviceGroup)
    {
        foreach (DeviceGroup dg in deviceGroup.DeviceGroups)
        {
            TreeViewItem groupTVI = new TreeViewItem();
            groupTVI.Header = dg;
            node.Items.Add(groupTVI);
            AddTreeItems(groupTVI, dg);
        }

        foreach (Device device in deviceGroup.Devices)
        {
            TreeViewItem deviceTVI = new TreeViewItem();
            deviceTVI.Header = device;
            node.Items.Add(deviceTVI);
        }
    }

LoadTree() is called after InitilizeComponent. The Xaml changed to: window resources:

        <HierarchicalDataTemplate DataType="{x:Type local:DeviceGroup}" ItemsSource="{Binding DeviceGroups}">
            <StackPanel>
                <TextBlock Text="{Binding Name}"/>
            </StackPanel>
        </HierarchicalDataTemplate>

with just a plain treeview in a grid.

Queso