Setting initial control focus

Topics: Prism v4 - WPF 4
Mar 7, 2012 at 4:28 PM

I'm curious if there's any special guidance regarding setting the initial control focus when using Prism. The reason I'm asking, of course, is that I've got some initial focus behavior that can best be described as "mildly psychotic" and I'm digging in to what I've done wrong.

For example, let's assume I have a shell with two regions and each of those regions has a single UserControl. Each UserControl has a single TextBox. Like this:

  • Shell
    • Region A
      • UserControlFoo
        • TextBox
    • Region B
      • UserControlBar
        • TextBox

What do I have to do to ensure that the TextBox in UserControlBar has focus when the shell is loaded? What if I remove UserControlBar from the region and add it back? Do I have to do something special to ensure that it gets focus (or doesn't)? What if I removed UserControlFoo from Region A and replaced it with UserControlBen? How would I specify where I wanted focus?

Thanks!

Greg

Developer
Mar 7, 2012 at 8:41 PM
Edited Mar 7, 2012 at 8:42 PM

Hi Greg,

As far as I know there is no guidance on this topic in Prism out-of-the-box.

I believe, a possible approach could be to give focus in the Loaded event in the UserControl of the element you want to get the focus. This way, if you have many UserControls, the last one loaded will be the one that receives the focus. However this approach might not be suitable for all scenarios as it won't give you much control. An example of this could be like the following code snippet:

public UserControlA()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(UserControlA_Loaded);
        }

        void UserControlA_Loaded(object sender, RoutedEventArgs e)
        {
            this.MyFocusableElement.Focus();
        }

Also, I believe you might the following threads interesting, where similar discussions are addressed:

Regards,

Agustin Adami
http://blogs.southworks.net/aadami

Mar 27, 2012 at 2:50 PM

Agustin,

Thanks for the pointers. In the end, I used the technique described in your first link and it works like a champ!

For those that may be using the Telerik WPF control suite's RadBusyIndicator (or similar), I also had to implement an attached behavior that would restore focus after the indicator "stole" focus when it displayed. The combination of the two behaviors fixed my solution right up.

-Greg