1
votes

I have a TreeView bound to an MVVM observable collection. My item template is composed by an image and a textblock like the following code show:

<HierarchicalDataTemplate x:Key="TreeViewItemTemplate" ItemsSource="{Binding Items, Mode=OneWay, NotifyOnSourceUpdated=True}">
    <TreeViewItem>
        <TreeViewItem.Header>
            <StackPanel Orientation="Horizontal">
                <Image 
                    Margin="-20,0,5,0"
                    Source="{Binding Icon, Converter={StaticResource TreeViewIconConverter}, Mode=OneWay}" 
                    Style="{DynamicResource SmallIcon}"/>
                <Label Content="{Binding Label}"/>
            </StackPanel>
        </TreeViewItem.Header>
    </TreeViewItem>
</HierarchicalDataTemplate>

The problem happens when you Click over an item. If the Mouse cursor is over the StackPanel, the selection will not happen. I have included also a screenshot to make this more clear. enter image description here

Of course this happens because the StackPanel is now over the selection area.

Is there any workaround?

1

1 Answers

1
votes

I found the answer by myself. When you customize the TreeView using an hierarchical data template then you should not replicate the TreeViewItem.Header template because at runtime WPF will create one for you. So, in order to have a custom TreeViewItem this code is enough:

<HierarchicalDataTemplate x:Key="TreeViewItemTemplate" ItemsSource="{Binding Items, Mode=OneWay, NotifyOnSourceUpdated=True}">
    <StackPanel Orientation="Horizontal">
        <Image 
            Margin="0,0,5,0"
            Source="{Binding Icon, Converter={StaticResource TreeViewIconConverter}, Mode=OneWay}" 
            Style="{DynamicResource SmallIcon}"/>
        <Label Content="{Binding Label}"/>
    </StackPanel>
</HierarchicalDataTemplate>