Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clicking TreeView item to select not working

I have a tree with a hierarchical data template

<HierarchicalDataTemplate DataType="{x:Type local:TreeItem}" ItemsSource="{Binding Path=Children}" >
   <TreeViewItem Focusable="True" ToolTip="{Binding ToolTipText}" >
      <TreeViewItem.Header>
         <StackPanel Orientation="Horizontal" Focusable="True" >
            <Image Width="16" Height="16" Margin="3,0">
               <Image.Source>
                  <Binding 
                                Path="IsLeaf" Converter="{StaticResource cnvIsBooleanToStringArrayItemConverter}">
                     <Binding.ConverterParameter>
                        <x:Array Type="sys:String">
                           <sys:String>..\Images\document_plain.png</sys:String>
                           <sys:String>..\Images\folder.png</sys:String>
                        </x:Array>
                     </Binding.ConverterParameter>
                  </Binding>
               </Image.Source>
            </Image>
            <TextBlock MaxWidth="300" Text="{Binding Desc}" Focusable="True" />
         </StackPanel>
      </TreeViewItem.Header>
   </TreeViewItem>
</HierarchicalDataTemplate>

I want to select an item by clicking at the TextBlock containing "Desc", but the only way to select an item is by clicking in the space left of the text (the image area)

Any clues what is missing?

Regards Klaus

like image 569
klawusel Avatar asked Dec 16 '22 16:12

klawusel


1 Answers

Your data template specifies a TreeViewItem at its root, but the TreeView will automatically create a TreeViewItem around your template, having a TreeViewItem in a TreeViewItem confuses the selection mechanism.

Do something like this:

    <HierarchicalDataTemplate DataType="{x:Type local:TreeItem}" ItemsSource="{Binding Path=Children}">
        <HierarchicalDataTemplate.ItemContainerStyle>
            <Style TargetType="TreeViewItem">
                <Setter Property="ToolTip" Value="{Binding ToolTipText}"/>
                <Setter Property="Focusable" Value="True"/>
                <Setter Property="Header">
                    <Setter.Value>
                        ...
                    </Setter.Value>
                </Setter>
            </Style>
        </HierarchicalDataTemplate.ItemContainerStyle>
    </HierarchicalDataTemplate>

Edit: After some testing it turns out that messing with the container is quite troublesome, i did not get it display the tooltip that way, unless you found a way to do it i recommend you stick to only setting HierarchicalDataTemplate.VisualTree (the default content of HierarchicalDataTemplate) which will be placed in the header of the auto-generated TreeViewItem.

like image 53
H.B. Avatar answered Jan 02 '23 23:01

H.B.