133

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?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
priyanka.sarkar
  • 25,766
  • 43
  • 127
  • 173

9 Answers9

180

In XAML:

<StackPanel FocusManager.FocusedElement="{Binding ElementName=Box}">
   <TextBox Name="Box" />
</StackPanel>
usefulBee
  • 9,250
  • 10
  • 51
  • 89
  • 11
    I prefer this approach to the others above since it keeps in line with MVVM. – Todd Sprang Feb 24 '14 at 15:05
  • 2
    Focused element is readonly right How can you set in xaml? I used this and it did not work – WPFKK Feb 05 '16 at 14:39
  • @user841612, check the following link and verify the Assembly and Namespace https://msdn.microsoft.com/en-us/library/system.windows.input.focusmanager.focusedelement%28v=vs.110%29.aspx – usefulBee Feb 10 '16 at 22:03
  • This only works once. If you want to change the focus after the page has been built, you need to do it programmatically. – Joe Steele Mar 20 '19 at 00:47
  • this works too. txtCompanyID.Focusable = true; Keyboard.Focus(txtCompanyID); – MindRoasterMir Aug 14 '20 at 13:10
  • This worked, however, I had to code the FocusManager.FocusedElement attribute on the outer-most container on my form (in my case a DockPanel), rather than on the DockPanel that directly contains the TextBox. – Sandra Jan 14 '23 at 12:37
71

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();
  }
}
Peter Huber
  • 3,052
  • 2
  • 30
  • 42
52

try FocusManager.SetFocusedElement

FocusManager.SetFocusedElement(parentElement, txtCompanyID)
Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184
31
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.

Noctis
  • 11,507
  • 3
  • 43
  • 82
Svetlozar Angelov
  • 21,214
  • 6
  • 62
  • 67
22

Try this : MyTextBox.Focus ( );

NazOok
  • 245
  • 2
  • 3
  • 2
    This is the most elegant answer and it doesn't require that you specify the parent as well. Thanks for this, it works great for me! – dbeachy1 Feb 20 '15 at 04:00
  • Peter Huber's answer does this but explains that the window needs to be loaded first, which is why mine was not working – Adriaan Davel Aug 28 '19 at 09:48
21

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}" />
Anya Hope
  • 1,301
  • 1
  • 17
  • 33
  • 6
    This worked for me also. The rest was not. Thanks for the link, that was quite interesting. Also interesting that such a simple thing can be so complicated. – TravisWhidden Oct 01 '15 at 04:05
  • 2
    The above answer works fine regardless if the container is a Gird or a StackPanel. Since the structure of your grid is not clear, it is hard to tell what could have went wrong. Nice to see alternatives though. – usefulBee Oct 22 '15 at 14:19
  • 1
    For me, this is also the only one to work correctly. Nice way. – OregonGhost Oct 07 '16 at 14:24
12

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.

vahlala
  • 355
  • 3
  • 14
anemomylos
  • 546
  • 1
  • 6
  • 14
1

In Code behind you can achieve it only by doing this.

 private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            txtIndex.Focusable = true;
            txtIndex.Focus();
        }

Note: It wont work before window is loaded

MindRoasterMir
  • 324
  • 1
  • 2
  • 18
0

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.

Alex Russkov
  • 323
  • 2
  • 8