当焦点丢失时,Treeview项目会丢失选择

时间:2021-12-03 22:16:55

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.

我已经在我正在处理的应用程序上注意到这一点,因此我创建了一个简单的测试应用程序来演示。下面是我的窗口和树视图项的事件处理程序。如果展开“一个”或“两个”父节点,并单击其中一个子节点,则在文本框上调用Focus()方法后,所选的子节点不会显示为已选中。而是选择弹出到父节点。有没有人知道如何克服这一点,并选择保留选定的子节点?谢谢。

<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

用上面的窗口和“Selected”事件处理

2 个解决方案

#1


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

通过这样做,为TreeView提供一些时间来完成他们的事件:

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

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

#2


Set TreeView.HideSelection to false.

将TreeView.HideSelection设置为false。

#1


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

通过这样做,为TreeView提供一些时间来完成他们的事件:

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

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

#2


Set TreeView.HideSelection to false.

将TreeView.HideSelection设置为false。