135

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?

2
  • txtCompanyID.Focusable = true; Keyboard.Focus(txtCompanyID); it works but this is how. Commented Aug 14, 2020 at 13:09
  • @MindRoasterMir working for me too. Commented Mar 17, 2022 at 18:12

9 Answers 9

183

In XAML:

<StackPanel FocusManager.FocusedElement="{Binding ElementName=Box}">
   <TextBox Name="Box" />
</StackPanel>
Sign up to request clarification or add additional context in comments.

7 Comments

I prefer this approach to the others above since it keeps in line with MVVM.
Focused element is readonly right How can you set in xaml? I used this and it did not work <Style.Triggers> <Trigger Property="Validation.HasError" Value="True"> <Setter Property="FocusManager.FocusedElement" Value="{Binding Source={RelativeSource Self}}"/> </Trigger> </Style.Triggers>
@user841612, check the following link and verify the Assembly and Namespace msdn.microsoft.com/en-us/library/…
This only works once. If you want to change the focus after the page has been built, you need to do it programmatically.
this works too. txtCompanyID.Focusable = true; Keyboard.Focus(txtCompanyID);
|
74

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();
  }
}

4 Comments

logically true , after too much struggle this answer is pretty good and perfect as solution.
this worked for me. the accepted answer didnt. Thanks
not sure if version specific, but Focus() requires focus state parameter - e.g. txtCompanyId.Focus(FocusState.Keyboard)
Yes, in Loaded event works.
54

try FocusManager.SetFocusedElement

FocusManager.SetFocusedElement(parentElement, txtCompanyID)

2 Comments

What if the element you want to set focus to is the parent element o.O?
FocusManager.SetFocusedElement(FocusManager.GetFocusScope(parentElement), parentElement);
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.

Comments

24

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}" />

4 Comments

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.
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.
For me, this is also the only one to work correctly. Nice way.
the only solution that worked in my case
23

Try this : MyTextBox.Focus ( );

2 Comments

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!
Peter Huber's answer does this but explains that the window needs to be loaded first, which is why mine was not working
14

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.

1 Comment

This answer deserves a better rank.
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

Comments

0

If looking for a WPF/Xaml solution, simply add focusable to the Object and the FocusManager code above. I don't know the answer to why the original code doesn't work.

i.e. <StackPanel x:Name="SqlInfoPanel" FocusManager.FocusedElement="{Binding ElementName=StudentNameText}" Width="800" Orientation="Horizontal" />

<TextBox x:Name="StudentNameText" Focusable="True" Text="{Binding StudentName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Height="33" VerticalAlignment="Top" Width="200">

2 Comments

Your answer doesn't provide more information than the previous answers, I think you should read the help center for answers and especially How to answer? and why your answer could be deleted. Then either edit your answer to add information that wasn't already provided by previous answers or simply delete yours
That is not true at all. The focusbehavior is only address below and as copied and pasted does not work. My solution shows that focusbehavior can be set inline when declaring the stackpanel and then setting focusable in the textbox itself. It's far more streamlined than whatever is in that Interaction.behaviors which threw errors. Also, this is the only example that shows how to set focusable in the XAML and not in the codebehind. Additionally, this bit of code, can be copied and pasted as IS without any edits. None of the ofter bits of code can do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.