I know this is old, but I ran across this issue today and in the end came up with this resolution:
Since the TextBox
is only being loaded when an item is selected, and that is when you want focus to be set, you can simply handle the TextBox.Load
event and call Focus()
.
There are two ways to achieve this.
1. Replace the TextBox
in the DataTemplate
with an AutoFocusTextBox
.
public class AutoFocusTextBox : TextBox
{
public AutoFocusTextBox()
{
Loaded += delegate { Focus(); };
}
}
Don't forget you'll need to reference the namespace in which AutoFocusTextBox is defined in your .xaml file.
2. Add a handler in the codebehind of the file where the DataTemplate
is defined.
SomeResourceDictionary.xaml
<TextBox Text="{Binding Something, Mode=TwoWay}" Style={StaticResource ...
Loaded="FocusTextBoxOnLoad" />
SomeResourceDictionary.xaml.cs
private void FocusTextBoxOnLoad(object sender, RoutedEventArgs e)
{
var textbox = sender as TextBox;
if(textbox == null) return;
textbox.Focus();
}
With either option, you can always add other behaviour in the handler, such as selecting all text.