views:

104

answers:

1

I am using a HierarchicalDataTemplate to bind my classes to a TreeView with checkboxes. I have the code working fine and everything is displayed fine, but I'd like to be able to get a list of children of an item in my treeview.

When a checkbox is clicked, I want to be able to select the parent nodes and child nodes. If I had access to the TreeViewItem that is supposed to wrap the checkbox then I could easily do this, but the Parent property of the Checkbox is null... I can only seem to gain access to my classes that are mapped in the HierarchicalDataTemplate.

<TreeView Margin="12" Name="trv1" SelectedItemChanged="trv1_SelectedItemChanged">
        <TreeView.Resources>
            <HierarchicalDataTemplate DataType="{x:Type src:Location}" ItemsSource="{Binding Path=Sublocations}">
                <CheckBox Content="{Binding Name}" Tag="{Binding}" IsChecked="{Binding IsChecked}" Click="checkBox_Click"/>
            </HierarchicalDataTemplate>

            <HierarchicalDataTemplate DataType="{x:Type src:Sublocation}" ItemsSource="{Binding Path=Children}">
                <CheckBox Content="{Binding Name}" Tag="{Binding}" IsChecked="{Binding IsChecked}" Click="checkBox_Click"/>
            </HierarchicalDataTemplate>

            <DataTemplate DataType="{x:Type src:Child}">
                <CheckBox Content="{Binding Name}" Tag="{Binding}" IsChecked="{Binding IsChecked}" Click="checkBox_Click"/>
            </DataTemplate>

        </TreeView.Resources>
    <TreeView.ItemContainerStyle>
        <Style TargetType="TreeViewItem">
            <Setter Property="IsSelected" Value="{Binding IsChecked}"/>
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>
A: 

I came up with a solution that may not be the optimal one, but it works. I added an EventSetter in the TreeView style and assigned a click event for TreeViewItem objects.

            <TreeView.ItemContainerStyle>
                <Style TargetType="TreeViewItem">
                    <Setter Property="IsSelected" Value="{Binding IsChecked}"/>
                    <EventSetter Event="Selected" Handler="tvi_Selected"/>
                </Style>
            </TreeView.ItemContainerStyle>

This way I can access the sender object, which is a TreeViewItem, and navigate through the nodes.

EDIT: This "solution" only gives me the top TreeViewItem object and not the selected one, which is a child of the object.

EDIT 2: The treeviewitems don't seem to actually let me access child treeviewitems or parent treeviewitems. I guess I was wrong.

Broker