2

I have a 2-level TreeView. Level-2 TreeViewItems contain TextBox controls via a data template.

What I want: if a TextBox control gets focus, the respective TreeViewItem is selected. I did some research and found this:

<Style TargetType="ListViewItem">
<Style.Triggers>
    <Trigger Property="IsKeyboardFocusWithin" Value="true">
        <Setter Property="IsSelected" Value="true" />
    </Trigger>
</Style.Triggers>

Link

This almost works perfectly if I replace ListViewItem by TreeViewItem.

But: The first child item always selects its parent item instead of itself. (The other child items work as expected).

So it's like

<TreeView>
<TreeViewItem>
  <TreeViewItem>  <-- this doesn't work
  <TreeViewItem>  <-- this works
</TreeViewItem>
<TreeViewItem>
  <TreeViewItem>  <-- this doesn't work
  <TreeViewItem>  <-- this works
  <TreeViewItem>  <-- this works
</TreeViewItem>
<TreeViewItem>
  <TreeViewItem>  <-- this doesn't work
  <TreeViewItem>  <-- this works
  <TreeViewItem>  <-- this works
</TreeViewItem>
...
</TreeView>

Any ideas what I am doing wrong or how to solve this?

Community
  • 1
  • 1
Golvellius
  • 1,928
  • 2
  • 13
  • 16

1 Answers1

3

I found a solution. It turned out that the problem was caused by the style being applied to the level-1 TreeViewItems as well (these only contain one TextBlock). So if I change the style to

            <Style TargetType="{x:Type TreeViewItem}">
                <Style.Triggers>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsKeyboardFocusWithin" Value="True"></Condition>
                            <Condition Property="HasItems" Value="False"></Condition>
                        </MultiTrigger.Conditions>
                        <MultiTrigger.Setters>
                            <Setter Property="IsSelected" Value="True"></Setter>
                        </MultiTrigger.Setters>
                    </MultiTrigger>
                </Style.Triggers>
            </Style>

and set this style as the <TreeView.ItemContainerStyle>, everything works as desired.

Golvellius
  • 1,928
  • 2
  • 13
  • 16