WPF
TextBox
Focus
User Interface
C#

Set focus on textbox in WPF

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Setting focus on a TextBox in WPF is easy when the UI is already loaded and visible. The tricky part is timing: focus requests often fail when they happen before layout has settled, when the control is hidden, or when the app tries to apply focus from the wrong layer.

Set Focus in Loaded

The most common solution is to set focus when the window or view finishes loading:

csharp
1using System.Windows;
2using System.Windows.Input;
3
4public partial class MainWindow : Window
5{
6    public MainWindow()
7    {
8        InitializeComponent();
9        Loaded += MainWindow_Loaded;
10    }
11
12    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
13    {
14        NameTextBox.Focus();
15        Keyboard.Focus(NameTextBox);
16    }
17}

Calling both Focus() and Keyboard.Focus() can improve consistency in some UI trees.

Use FocusManager.FocusedElement for Simple XAML Cases

If all you want is an initial focus target, XAML can sometimes be enough:

xml
1<Window x:Class="FocusDemo.MainWindow"
2        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4        FocusManager.FocusedElement="{Binding ElementName=NameTextBox}">
5    <Grid>
6        <TextBox x:Name="NameTextBox" Width="220" Height="28" />
7    </Grid>
8</Window>

This is useful for simple startup focus scenarios where the control is already visible.

When Loaded Is Still Too Early

In more complex views, focus in Loaded can still fail because templates, animations, or delayed visibility have not finished. In that case, use the dispatcher to postpone the focus request:

csharp
1using System;
2using System.Windows.Input;
3using System.Windows.Threading;
4
5Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new Action(() =>
6{
7    NameTextBox.Focus();
8    Keyboard.Focus(NameTextBox);
9}));

This lets layout and rendering complete before the focus request runs.

The Control Must Be Visible and Focusable

WPF will not focus a control that is:

  • collapsed
  • inside an inactive tab
  • disabled
  • not focusable

So if focus appears to "do nothing," first confirm the control is actually in a state where focus is possible.

MVVM-Friendly Attached Behavior

In MVVM applications, repeated code-behind focus logic becomes noisy. An attached property is a common alternative:

csharp
1using System.Windows;
2using System.Windows.Input;
3
4public static class FocusBehavior
5{
6    public static readonly DependencyProperty IsFocusedProperty =
7        DependencyProperty.RegisterAttached(
8            "IsFocused",
9            typeof(bool),
10            typeof(FocusBehavior),
11            new PropertyMetadata(false, OnIsFocusedChanged));
12
13    public static void SetIsFocused(DependencyObject element, bool value) =>
14        element.SetValue(IsFocusedProperty, value);
15
16    public static bool GetIsFocused(DependencyObject element) =>
17        (bool)element.GetValue(IsFocusedProperty);
18
19    private static void OnIsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
20    {
21        if (d is UIElement ui && (bool)e.NewValue)
22        {
23            ui.Focus();
24            Keyboard.Focus(ui);
25        }
26    }
27}

This gives you a reusable, view-friendly focus hook without putting focus code in every window.

Dialogs and Tab Controls Need Extra Care

If the target TextBox sits inside a tab, expander, or custom dialog, make sure that container is already active before requesting focus. WPF does not raise an obvious error when focus is asked of a control that is technically present but not currently reachable in the active visual path.

Focus After Validation Errors

A common user-experience pattern is to return focus to the first invalid field after validation. That works well in WPF, but it still obeys the same rules: the target control must be visible, enabled, and ready in the visual tree.

That is why focus bugs are often really state bugs rather than API bugs.

Common Pitfalls

  • Calling Focus() before the control is loaded and visible.
  • Trying to focus a TextBox inside an inactive tab or collapsed panel.
  • Forgetting that the target control must be focusable and enabled.
  • Scattering focus logic across many code-behind files instead of using one reusable pattern.
  • Assuming the API is broken when the real issue is visual-tree timing.

Summary

  • Set focus in Loaded for straightforward windows and dialogs.
  • Use FocusManager.FocusedElement for simple declarative startup focus.
  • If timing causes failures, defer the focus request through the dispatcher.
  • Make sure the target control is visible, enabled, and focusable.
  • In MVVM applications, use an attached behavior to keep focus logic reusable and clean.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.