Treeview Item Loses Selection When Focus Is Lost

心已入冬 提交于 2019-12-07 13:31:00

问题


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


回答1:


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

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




回答2:


Set TreeView.HideSelection to false.



来源:https://stackoverflow.com/questions/1003883/treeview-item-loses-selection-when-focus-is-lost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!