Silverlight 4 – How to focus a TextBox that is contained in your Custom Control on Startup

Silverlight 4 – How to focus a TextBox that is contained in your Custom Control on Startup

Focusing a TextBox that’s inside a Custom Control isn’t so easy at startup of your application. Let me explain the problem that is also discussed on http://forums.silverlight.net/forums/t/151235.aspx. Imagine you’ve created a custom control that has a TextBox as Part-element. The Style that sets the Template would look like this:

You get the TextBox from the Template in the OnApplyTemplate-Method

Now imaginge you want to focus your SimpleControl in the constructor of your MainPage like below:

The Problem that occurs is that the OnApplyTemplate-Method is called after the Focus-Method. So you don’t have the TextBox defined in your Template. The Solution is very easy. Just hide the Focus-Method from the base-class and set a flag. But keep in mind that this won’t work if you store your SimpleControl in a variable of type Control, cause then no polymorphic call is made to the Focus-Method defined in SimpleControl. Here a sample implementation:

Share this post