WPF: Setting Keyboard Focus in a User Control? (Problems with KeyBinding)

烈酒焚心 提交于 2020-01-22 14:20:07

问题


I have an app that has a main window that contains a bunch of stuff. From time to time the user will do something in response to which I want to display something else entirely in the main window, temporarily hiding what is there.

I'm doing this by making the outermost element in the main window a Grid with no rows or columns defined. Every element in the grid, then will completely fill the one single cell in the grid, drawing on top of the others.

My regular bunch stuff, then, is in the first element of the grid, and my temporary something else is a UserControl as the second element of the grid, that is normally set Visibility=Collapsed.

Except for the KeyBinding everything works fine. When the appropriate command is triggered in the regular bunch of stuff, the visibility on the UserControl is set to Visible, and it covers the regular bunch of stuff completely. When the user clicks on the close button on the UserControl, it's visibility is set to Collapsed, again, and it disappears and the regular bunch of stuff is revealed.

My problem is with KeyBindings. I have a few defined on the UserControl - that should not be defined on the main window - and they don't work. Or rather, they work fine once I click inside the UserControl, but they don't work until I do.

I need them to work as soon as the UserControl is made visible, without requiring the user to click or tab into the UserControl proper.

My guess is that this has something to do with keyboard focus - but I've been unable to find a way to set the focus on the UserControl. Here's the thing - the only element within the UserControl is a tab control, all of the tabs of which are dynamically constructed via templates. There are no elements known at compile time that I can reference explicitly and pass to KeyBoard.Focus().

So, am I right in thinking that it's lack of focus that is causing the problem? And if so, how can I set focus to an element in a TabControl, when I don't even know how many tabs there are, let alone which is the selected one?


回答1:


I wanted this control to have the focus, when it became visible. So in the constructor, I set up a handler on IsVisibleChanged.

public MyControl
{
    ...
    this.IsVisibleChanged += new DependencyPropertyChangedEventHandler(MyControl_IsVisibileChanged);
}

void MyControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    if (!(bool(e.NewValue)
        return;
    this.Focusable = true;
    Keyboard.Focus(this);
}

I could have set Focusable in the xaml, but I prefer it in the code-behind, so that all of the relevant code is in one place.



来源:https://stackoverflow.com/questions/12866392/wpf-setting-keyboard-focus-in-a-user-control-problems-with-keybinding

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