How to set the focus on an TextBox
element in WPF
I have this code:
txtCompanyID.Focusable = true;
txtCompanyID.Focus();
...but it is not working.
Any idea?
Nobody explained so far why the code in the question doesn't work. My guess is that the code was placed in the constructor of the Window. But at this time it's too early to set the focus. It has to be done once the Window is ready for interaction. The best place for the code is the Loaded event:
public KonsoleWindow() {
public TestWindow() {
InitializeComponent();
Loaded += TestWindow_Loaded;
}
private void TestWindow_Loaded(object sender, RoutedEventArgs e) {
txtCompanyID.Focus();
}
}
txtCompanyID.Focusable = true;
Keyboard.Focus(txtCompanyID);
msdn:
There can be only one element on the whole desktop that has keyboard focus. In WPF, the element that has keyboard focus will have IsKeyboardFocused set to true.
You could break after the setting line and check the value of IsKeyboardFocused
property. Also check if you really reach that line or maybe you set some other element to get focus after that.
None of this worked for me as I was using a grid rather than a StackPanel.
I finally found this example: http://spin.atomicobject.com/2013/03/06/xaml-wpf-textbox-focus/
and modified it to this:
In the 'Resources' section:
<Style x:Key="FocusTextBox" TargetType="Grid">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=textBoxName, Path=IsVisible}" Value="True">
<Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=textBoxName}"/>
</DataTrigger>
</Style.Triggers>
</Style>
In my grid definition:
<Grid Style="{StaticResource FocusTextBox}" />
In case you haven't found the solution on the other answers, that's how I solved the issue.
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
TEXTBOX_OBJECT.Focus();
}), System.Windows.Threading.DispatcherPriority.Render);
From what I understand the other solutions may not work because the call to Focus()
is invoked before the application has rendered the other components.
Another possible solution is to use FocusBehavior provided by free DevExpress MVVM Framework:
<TextBox Text="This control is focused on startup">
<dxmvvm:Interaction.Behaviors>
<dxmvvm:FocusBehavior/>
</dxmvvm:Interaction.Behaviors>
</TextBox>
It allows you to focus a control when it's loaded, when a certain event is raised or a property is changed.