views:

18

answers:

2

Hi, how can I get the constituent controls making up the TreeViewItem in code if they are inside a hierarichicaldatatemplate?

 <HierarchicalDataTemplate DataType="{x:Type local:Module}" ItemsSource="{Binding Children}">
            <StackPanel Orientation="Horizontal">
                <Image Width="16" Height="16" Margin="3,0" Source="Images\module.ico" />
                <local:RenamingNode Name="RenamableNode" Text="{Binding Name}" VstaObject="{Binding BindsDirectlyToSource=True}" OnRename="OnRenameOccured"  />
            </StackPanel>
        </HierarchicalDataTemplate>

So programatically when I get an event with a TreeViewItem as the source, I want to be able to get the local:RenamingNode, but I can't get the TreeViewItem's descendants.

Thanks,

Ilya

A: 

You can use FrameworkTemplate.FindName to find the header content presenter in the TreeView item control template, and then again to find the part you want in the data template.

private object FindContentTemplatePart(TreeViewItem treeViewItem)
{
    if (treeViewItem != null)
    {
        var header = treeViewItem.Template.FindName("PART_Header", treeViewItem) as ContentPresenter;
        if (header != null)
        {
            return header.ContentTemplate.FindName("RenamableNode", header);
        }
    }
    return null;
}

You could also walk the visual tree manually with the methods on VisualTreeHelper.

Quartermeister
A: 

I'm assuming that this will be the same in WPF as silverlight (this is the silverlight version)

(treeViewItem.HeaderTemplate.LoadContent() as StackPanel).FindName("RenamableNode")

Druzil