ross dickinson: web and desktop software developer

Preventing Focus Loss in WPF

by Ross on August 19, 2010 at 3:15 PM under Programming | WPF

For my program, Crunch, I'm trying to create a program that will be easy to convert between WPF and Silverlight. While they're the same for the most part, the two have a few differences that can lead to annoying compatibility issues. One of these is WPF's lack of Silverlight's ChildWindow class. The ChildWindow class allows for modal dialogs to pop up inside the Silverlight application itself, removing the need from breaking out of the web browser and showing a window.

Sadly, WPF doesn't have this feature. I've been able to work around this by making my own ModalDialog class. I'm not going into details on that, but one aspect that was annoying me recently.

When a ModalDialog instance displays inside its owning Window, the Window displays a container grid to cover up everything underneath. This works great for preventing mouse access of underlying controls and changing focus while the dialog is open, but this does nothing for keyboard navigation. A user could still hit tab and tab out of the control, leading to any number of problems!

The first thing I tried was disabling all underlying controls. This worked, but it seemed hacky and made the layout pretty ugly.

After some searching, I found there's two simple lines of code I can use to get around this issue. With these two properties set, keyboard focus is trapped within the container until either the property is changed, or another control is forcibly focused through code.

'Locks the tab key to the focused control

KeyboardNavigation.SetTabNavigation(modalContainerGrid, KeyboardNavigationMode.Cycle)

'Locks the tab key to the focused control if the user's also holding down Ctrl

KeyboardNavigation.SetControlTabNavigation(modalContainerGrid, KeyboardNavigationMode.Cycle)

I hope this helps someone in the future!

About the author

rossisdead is a 26 year old web and desktop software developer from New Jersey. He has two cats and likes long walks on the beach.

On Stackoverflow

On Stackoverflow Careers

On Codeplex

On Github