Search code examples
wpftreeviewtreeviewitem

wpf TreeViewItem is not selectable


I've made a TreeView UserControl using this code:

<UserControl x:Class="Company.ObjectInTreeView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:Company"
         mc:Ignorable="d" 
         d:DesignHeight="450" d:DesignWidth="800"
         x:Name="ObjectInTreeViewControl">
<TreeView ItemsSource="{Binding TreeNodes, ElementName=ObjectInTreeViewControl}" SelectedItemChanged="TreeView_SelectedItemChanged">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="ToolTip" Value="{Binding ToolTipText}"/>
            <Setter Property="Background" Value="Transparent"/>
        </Style>
    </TreeView.ItemContainerStyle>
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:TreeNode}" ItemsSource="{Binding Path=Children}">
            <TreeViewItem IsSelected="{Binding IsSelected, Mode=TwoWay}" IsExpanded="{Binding IsExpanded, Mode=TwoWay}" Selected="TreeViewItem_Selected" Expanded="TreeViewItem_Expanded" MouseLeftButtonUp="TreeViewItem_MouseLeftButtonUp">
                <TreeViewItem.Header>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Path=Value}" />
                    </StackPanel>
                </TreeViewItem.Header>
            </TreeViewItem>
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>

only empty space of TreeViewItem is selectable, and the user can't select an item by click on the text of the item

Only the yellow parts are clickable and selectable: only the yellow parts are clickable and selectable

is there anyone to help me find and correct my mistake?


Solution

  • I've found the problem!

    I only changed TreeView.Resources like this:

    <TreeView.Resources>
            <HierarchicalDataTemplate DataType="{x:Type local:TreeNode}" ItemsSource="{Binding Path=Children}">
                <Grid>
                    <TextBlock Text="{Binding Path=Value}"/>
                    <TreeViewItem Selected="TreeViewItem_Selected" Expanded="TreeViewItem_Expanded" MouseLeftButtonUp="TreeViewItem_MouseLeftButtonUp"></TreeViewItem>
                </Grid>
            </HierarchicalDataTemplate>
        </TreeView.Resources>
    

    Good luck