5
votes

I have noticed this on an application I am working on right now, so I created a simple test app to demonstrate. Below is my a window and the event handler for the treeview items. If you expand either the "One" or "Two" parent nodes, and click one of the children, the child that was selected does not show up as selected after the Focus() method is called on the text box. Instead, selection pops to the parent node. Does anyone have any idea how to overcome this, and have the selection remain with the selected child node? Thanks.

<Window 
x:Class="DockingSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1"
WindowState="Maximized"
>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="300" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TreeView Margin="6">
        <TreeViewItem Header="One">
            <TreeViewItem Header="One" Selected="TreeViewItem_Selected" />
            <TreeViewItem Header="Two" Selected="TreeViewItem_Selected" />
            <TreeViewItem Header="Three" Selected="TreeViewItem_Selected" />
        </TreeViewItem>
        <TreeViewItem Header="Two">
            <TreeViewItem Header="One" Selected="TreeViewItem_Selected" />
            <TreeViewItem Header="Two" Selected="TreeViewItem_Selected" />
            <TreeViewItem Header="Three" Selected="TreeViewItem_Selected" />
        </TreeViewItem>
    </TreeView>

    <TextBox Grid.Column="1" x:Name="textbox" />
</Grid>

private void TreeViewItem_Selected(object sender, RoutedEventArgs e)
    {
        textbox.Focus();
    }

With the above window and the "Selected" event handl

2
Just a little refactoring comment, instead of putting the Selected event in each treeview item, you can: <TreeView Margin="6" TreeViewItem.Selected="TreeViewItem_Selected" />;apandit
And it seems that double clicking the child element works correctly but not single clicking... :Sapandit
Yeah, I know that, but in this case, I don't want the parent nodes to actually cause the action to happen, only the children. I would assume double clicking "works" because the second click recaptures focus to the treeview, and even though the parent is highlighted, the child is probably still marked as selected so it doesn't get selected again on the second click. The question remains though, why does the highlighting shift to the parent when the treeview loses focus?uncle hammy
I would assume it's a bug in WPF. Report it perhaps?apandit

2 Answers

4
votes

Give some time for TreeView to finish their events by doing this instead:

Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() => textbox.Focus()));

-2
votes

Set TreeView.HideSelection to false.