3

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?

Thomas
  • 555
  • 7
  • 29

2 Answers2

6

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

0

you can also use this with <window> tag of the xaml page

<Window x:Class="WpfApplication30.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" 
FocusManager.FocusedElement="{Binding ElementName=SearchBox}">
<StackPanel>
<TextBox x:Name="textBox1"/>
<TextBox x:Name="SearchBox"
style="{StaticResource SearchBox}" />
</StackPanel>
</Window>
AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57
  • Thank you for your response, but this was the original code I was using `FocusManager.FocusedElement="{Binding ElementName=SearchBox}">` but unfortunately, that only sets the logical focus. I've implemented the accepted solution above and it works well! – Thomas Nov 06 '18 at 17:40