Keyboard.Focus does not work on text box in WPF

后端 未结 3 1214
庸人自扰
庸人自扰 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:09

    If it helps anyone I had this problem and my application had a main window with multiple user controls placed in separate grids with a visibility data binding. Because the grids were there when the application was built the .Focus() called on Loaded or Constructor would be called at the build time, not at visibility time.

    Anyhow I fixed it by calling .Focus() on MouseEnter event of the grid. Works fine for me.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-01 19:19

    Building on Rachel's solution there is a simpler way.

    in XAML add to the TextBox Loaded="Got_Loaded"

    and in code behind

        private void Got_Loaded(object sender, RoutedEventArgs e)
        {
            Keyboard.Focus(((TextBox)sender));
        }
    
    0 讨论(0)
提交回复
热议问题