WPF TreeViewItem无法选择

时间:2019-01-07 16:02:22

标签: wpf treeview treeviewitem

我使用以下代码制作了TreeView UserControl:

<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>

只能选择TreeViewItem的空白空间,并且用户无法通过单击项目文本来选择项目

只有黄色部分可以单击和选择: only the yellow parts are clickable and selectable

有没有人可以帮助我发现并纠正我的错误?

1 个答案:

答案 0 :(得分:0)

我找到了问题!

我只更改了TreeView。资源如下:

<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>

祝你好运