Search code examples
c#wpfxaml

TextBox is Focused, but Can't Type Until I Click - XAML/C#/WPF


I have an interesting situation where I set the focus on a searchbox using: FocusManager.FocusedElement="{Binding ElementName=SearchBox}" which I found here: Set the focus on a textbox in xaml wpf

The good thing is that the search box is actually focused (I have a trigger that performs an action on focus), but I can't type into the textbox until I click on the textbox.

My textbox is very basic:

<TextBox x:Name="SearchBox"
         Grid.Row="0"
         style="{StaticResource SearchBox}" />

Any idea how I can allow the user to type right away as they open the control?


Solution

  • See the following link: https://learn.microsoft.com/en-us/dotnet/api/system.windows.input.focusmanager.focusedelement?redirectedfrom=MSDN&view=netframework-4.7.2#System_Windows_Input_FocusManager_FocusedElement

    Especially the remarks:

    The FocusedElement is the element which has logical focus for a specific focus scope. This object may or may not have keyboard focus. Keyboard focus refers to the element that receives keyboard input. For more information on focus, keyboard focus, and logical focus, see the Input Overview.

    and: https://learn.microsoft.com/en-us/dotnet/api/system.windows.input.focusmanager?redirectedfrom=MSDN&view=netframework-4.7.2

    An element with logical focus does not necessarily have keyboard focus, but an element with keyboard focus will have logical focus. It is possible to define a focus scope within a focus scope. In this case, both the parent focus scope and the child focus scope can have a FocusManager.FocusedElement

    In the following post you'll find an example how to handle this: https://stackoverflow.com/a/20299923/9295125