Click here to Skip to main content
15,860,972 members
Articles / Desktop Programming / WPF
Tip/Trick

Setting Focus to a Control inside a usercontrol in WPF

Rate me:
Please Sign up or sign in to vote.
4.93/5 (35 votes)
17 Oct 2012CPOL3 min read 138.2K   11   41
Workaround for a bug concerning focus of child controls inside WPF UserControl
In this tip, you will see a solution to a bug concerning focus of child controls inside a WPF UserControl.

Introduction

This is my scenario: I have a login usercontrol in my WPF application that is shown in the main form. On that, I have a UserName textbox and a Password passwordbox. When a login is successful, I save the username for the next application run and automatically populate the username box with it so that the user does not have to type it again (if it is indeed the same user - which it is in 99.9% of the cases).

So I want my login control to set focus to the username textbox if it is empty and to the passwordbox if the username is filled in.

That proved to be a very difficult task. I must have tried at least 30 different solutions to get that to happen, but they didn't work. No matter WHAT I did, NONE of the boxes would be focused.

Background

First, I tried simply setting focus to the desired control in the Usercontrols constructor (after the Initialize call of course) using:

C#
txtPassword.Focus();  

That doesn't work. I also tried the keyboard method:

C#
Keyboard.Focus(txtPassword); 

And (even though that wasn't what I wanted), I tried the XAML FocusManager method:

XML
FocusManager.FocusedElement="{Binding ElementName=txtPassword}" 

No, nothing of that worked.

I noticed the property Focusable and set it to true (didn't help, and it turned out in the end that it wasn't even necessary to set it).

I tried the two first methods again, but tried to put them in the Loaded event, in the GotFocus event, etc.

I tried setting focus to the parent controls and the entire usercontrol from the MainForm.

I tried from a different thread - Nope, didn't work!

I tried several combinations of Dispatcher.BeginInvoke, but to no avail.

I tried using Sleep(); before the focus events, didn't work...

All articles I found on Google had different solutions, and none of them worked. Some articles claimed it was a bug and that it had been reported to Microsoft. But that wasn't much help of course.

The Code that Did the Trick

After more than 3 hours of trial and error - just on the verge of breakdown, and the painful realization that I ought to just accept that the user was forced to manually click the box to enter the information - I finally came across this:

C#
//Constructor
public LoginControl()
{
	InitializeComponent();
	this.IsVisibleChanged += new DependencyPropertyChangedEventHandler
                             (LoginControl_IsVisibleChanged); 
}

void LoginControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
	if ((bool)e.NewValue == true)
	{
		Dispatcher.BeginInvoke(
		DispatcherPriority.ContextIdle,
		new Action(delegate()
		{
			txtPassword.Focus();
		}));
	} 
}  

Thanks a lot to Oli on StackOverflow - I FINALLY got the problem solved.

Please note: The code above is simplified and just concerns setting the focus to a given control. As you would recall, I wanted the focus to be set on different control based on whether or not one of them contained text. But since it is trivial to adapt the code above for that, I have chosen to keep the eye on the ball.

Finally

I really can't help thinking: Why the heck does it have to be so difficult to solve such a simple problem????

It took me +3 hours just to solve such a reasonably irrelevant issue - time that could have been used to develop far more interesting features.

There might be other solutions, but I've got the problem solved now... I simply decided to share this tip with you if any of you should have the same problem (and also to be able to remember it myself next time).

History

  • 17th October, 2012: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Sweden Sweden
Born in Copenhagen, Denmark
Have been living in Paris, France and L.A., The United States
Now live in Stockholm, Sweden

Started programming when I got my first VIC 20, and a few months later on Commodore 64. Those were the days!

Studied programming at the Copenhagen Engineering Academy

Professional console, winforms and webforms programming in Comal, x86 Assembler, Fortran, Pascal, Delphi, Visual Basic 3 through 6, Classic ASP, C# and VB.NET

I now work as Senior Microsoft Dynamics AX and .Net programmer, and have a number of projects in various states of progress to work on in the spare time...

Comments and Discussions

 
PraiseAbsolute Star Pin
SammyW21-Jul-20 12:39
SammyW21-Jul-20 12:39 
QuestionIt's 2020 and this still works. Pin
Jinx1012-Jul-20 14:59
Jinx1012-Jul-20 14:59 
QuestionWill this work with MVVM? Pin
Member 974516310-Feb-20 0:59
Member 974516310-Feb-20 0:59 
PraiseSet Focus to control inside usercontrol in WPF Pin
Member 133931419-Feb-18 9:58
Member 133931419-Feb-18 9:58 
SuggestionLoaded Event Pin
Schuttrim8-Jun-17 2:58
Schuttrim8-Jun-17 2:58 
GeneralRe: Loaded Event Pin
Johnny J.8-Jun-17 3:13
professionalJohnny J.8-Jun-17 3:13 
Question+1 Pin
Zangl Ltd12-Sep-16 2:50
Zangl Ltd12-Sep-16 2:50 
AnswerRe: +1 Pin
Johnny J.12-Sep-16 2:53
professionalJohnny J.12-Sep-16 2:53 
QuestionThank you! Pin
GregScott33319-Jul-16 20:36
GregScott33319-Jul-16 20:36 
AnswerRe: Thank you! Pin
Johnny J.20-Jul-16 1:26
professionalJohnny J.20-Jul-16 1:26 
Answermove the control.focus() to form shown event Pin
Member 1165821015-Nov-15 3:55
Member 1165821015-Nov-15 3:55 
GeneralRe: move the control.focus() to form shown event Pin
Johnny J.20-Jul-16 1:26
professionalJohnny J.20-Jul-16 1:26 
GeneralRe: move the control.focus() to form shown event Pin
Buzz Weetman6-Feb-17 2:59
Buzz Weetman6-Feb-17 2:59 
GeneralRe: move the control.focus() to form shown event Pin
Member 1239601522-Apr-20 10:25
Member 1239601522-Apr-20 10:25 
QuestionXaml view is not displaying Pin
LahD15-Oct-15 18:42
LahD15-Oct-15 18:42 
QuestionXaml vieiw is not displaying Pin
LahD15-Oct-15 18:42
LahD15-Oct-15 18:42 
QuestionThanks very much! Pin
cbrack66630-Sep-15 11:28
cbrack66630-Sep-15 11:28 
GeneralThanks for this solution Pin
ashavi27-Sep-15 1:07
professionalashavi27-Sep-15 1:07 
QuestionHow to achieve the same in the MVVM ??? Pin
kaliprasad12311-May-15 1:14
kaliprasad12311-May-15 1:14 
AnswerRe: How to achieve the same in the MVVM ??? Pin
Johnny J.18-May-15 19:35
professionalJohnny J.18-May-15 19:35 
GeneralRe: How to achieve the same in the MVVM ??? Pin
tridy3-Sep-15 5:16
tridy3-Sep-15 5:16 
SuggestionMust use System.Windows.Threading Pin
PLCI18-Mar-15 8:02
PLCI18-Mar-15 8:02 
GeneralRe: Must use System.Windows.Threading Pin
Johnny J.18-May-15 19:34
professionalJohnny J.18-May-15 19:34 
GeneralSaved my day ! Pin
karthik cad/cam24-Feb-15 1:40
karthik cad/cam24-Feb-15 1:40 
QuestionGreat!! thanks! Pin
caradri20-Oct-14 22:37
caradri20-Oct-14 22:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.