Click here to Skip to main content
Click here to Skip to main content

Tagged as

Setting focus to a control inside a usercontrol in WPF

, 17 Oct 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
How to work around 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 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: 

txtPassword.Focus();  

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

Keyboard.Focus(txtPassword); 

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

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:  

//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 it 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). 

License

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

Share

About the Author

Johnny J.
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 .NET developer building Airline Booking Systems, and have a number of projects in various states of progress to work on in the spare time...
 
PS: The cat on my profile is one of my three cats, Ramses. He's all white, odd-eyed, deaf and definitely the coolest cat there is!

Comments and Discussions

 
QuestionGreat!! thanks! Pinmembercaradri20-Oct-14 23:37 
GeneralMy vote of 5 PinmemberMember 1090953822-Sep-14 23:10 
GeneralTHANK YOU!!!!!!!! PinmemberMember 99167377-Aug-14 8:03 
GeneralMy vote of 3 PinmemberGilberto Alexandre12-Jul-14 14:16 
Questionthank you for your help PinmemberDaniel Dwire29-Apr-14 3:26 
QuestionMany thanks PinmemberDaryl Lucas28-Mar-14 18:24 
QuestionMany thanks Pinmemberpiotrjurasinski19-Mar-14 23:16 
Questiongreat Pinmembertaleofsixstrings13-Mar-14 0:06 
QuestionVery good Pinmemberfirstvic6-Mar-14 4:11 
QuestionSetting focus to a control inside a usercontrol in WPF Pinmemberrk288110-Jan-14 9:46 
AnswerRe: Setting focus to a control inside a usercontrol in WPF PinprofessionalJohnny J.10-Jan-14 11:25 
GeneralNice snippet... PinmemberCrazyTasty3-Dec-13 7:55 
GeneralRe: Nice snippet... PinprofessionalJohnny J.3-Dec-13 8:40 
Answerthe Focusable and the IsVisible properties on the base elements must be set to true Pinmembersacpundir26-Sep-13 2:31 
GeneralRe: the Focusable and the IsVisible properties on the base elements must be set to true PinprofessionalJohnny J.28-Sep-13 0:05 
GeneralMy vote of 5 PinmemberMalicious Demon31-Jul-13 23:07 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411022.1 | Last Updated 17 Oct 2012
Article Copyright 2012 by Johnny J.
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid