Keyboard.Focus does not work on text box in WPF

后端 未结 3 1213
庸人自扰
庸人自扰 2021-02-01 18:56

I am banging my head on what looks like such a simple problem to fix in wpf but i have yet to discover why i can\'t get my app to behave according to my plan.

I have a

3条回答
  •  别那么骄傲
    2021-02-01 19:10

    As a workaround, you could try using the Dispatcher to set the focus at a later DispatcherPriority, such as Input

    Dispatcher.BeginInvoke(DispatcherPriority.Input,
        new Action(delegate() { 
            SearchCriteriaTextBox.Focus();         // Set Logical Focus
            Keyboard.Focus(SearchCriteriaTextBox); // Set Keyboard Focus
         }));
    

    From the description of your problem, it sounds like you don't have Keyboard focus set. WPF can have multiple Focus Scopes, so multiple elements can have Logical Focus (IsFocused = true), however only one element can have Keyboard Focus and will receive keyboard input.

    The code you posted should set the focus correctly, so something must be occurring afterwards to move Keyboard Focus out of your TextBox. By setting focus at a later dispatcher priority, you'll be ensuring that setting keyboard focus to your SearchCriteriaTextBox gets done last.

提交回复
热议问题