对焦控制不起作用

Focusing control doesn't work

我有一个 Window 填充了 TreeView 和其他控件。当用户选择了 TreeView 的一个项目后,我想在按下 Enter 键时触发一个命令,然后将焦点切换到 TreeView,以便可以看到选择。

命令调用适用于此代码:

<Window ...>
    ...
    <Window.InputBindings>
        <KeyBinding Command="{Binding Path=MyCommand}" Key="Enter"/>
    </Window.InputBindings>
    ...
    <TreeView x:Name="tv" ...>
        ...
    </TreeView>
</Window>

但我不知道如何在执行命令后将焦点更改到TreeView。我如何在 XAML 或代码隐藏中执行此操作? XAML 优先回答。

这是我试过的:

<Window.InputBindings>
    <KeyBinding Command="{Binding Path=ChangeCategoryCommand}" Key="Enter" FocusManager.FocusedElement="{Binding ElementName=tv}"/>
</Window.InputBindings>

但是按下回车后TreeView中的选择不可见,所以我显然做错了...

只有一个代码隐藏解决方案:

<Window 
PreviewKeyUp="OnPreviewKeyUp">
<Window.InputBindings>
    <KeyBinding Key="Enter" Command="{Binding Path=MyCommand}" />
</Window.InputBindings>

<TreeView x:Name="tv" />

和隐藏代码:

private void OnPreviewKeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            this.tv.Focus();
        }
    }

仅供参考:树视图的选定项目是只读的,因此不能真正用于绑定。