views:

279

answers:

1

I have the following XAML:

<TreeView>
   <TreeViewItem ItemsSource={Binding} Header="TopMost" IsExpanded="True">
      <TreeViewItem.ItemTemplate>
         <DataTemplate>
            <TreeViewItem>
              <TreeViewItem.Header>
                <TextBlock Text="{Binding SubTopic}"/>
              <TreeViewItem.Header>
              <!-- further data representation -->
            </TreeViewItem>
        </DataTemplate>
      </TreeViewItem.ItemTemplate>
   </TreeViewItem>
   <TreeViewItem>
   </TreeViewItem>
</TreeView>

The first TreeViewItem does expand and show its children, but the selector that should be visible on the left of the text TopMost is not present. I can get the children of the main TreeViewItem to collaps and expand by double clicking the TopMost Header. How do I solve this?

+2  A: 

Your XAML works fine in a default WPF project except for a typo (I changed the second <TreeViewItem.Header> to </TreeViewItem.Header>). When I run it I see the selector (little triangle) beside the word "TopMost", and it works correctly.

I would:

  • Look to see if you've overridden the style for TreeViewItem or TreeView at any point.
  • Explore the generated visual tree at runtime (using VS.NET debugger or a tool like Mole) to see if the ToggleButton is present in the Visual tree as the first child of the Grid. (The default template for TreeViewItem uses a ToggleButton not an Expander)
  • Try a separate with one child to see if it works. If it does, incrementally change both until you find the problem.

Note

There's no law that says you can't use TreeViewItems inside DataTemplates like you are doing, but it usually is not a good idea because it defeats the purpose of the <TreeView>, which is to provide selection, focus, and accessibility support to multiple TreeViewItems.

You will find that:

  1. Your TreeView does not track your selected item except at the top level
  2. You can select items in your "tree" independently, for example you can select multiple items and they don't realize it. Like checkboxes instead of radio buttons.
  3. If you omit the <TreeView> tag entirely it will still run fine.

This is because TreeView is not able to do its job: The DataTemplate is hiding the TreeViewItems from the TreeView so it only sees the top-level items. Check out HierarchicalDataTemplate for a good way to enable the TreeView object to see the whole tree.

Ray Burns
Thanks for your extensive answer. I still am not sure what caused the expander button to disappear, but it did come back when I implemented a HierarchicalDataTemplate.
Dabblernl