WPF Initial Focus

A violation of rule of least astonishment: in Windows Forms the focus is automatically set to the first element in tab order. In WPF (and in ASP.NET) it’s not the case. You need to specify the initial focus element explicitly.

A trivial way to do it is to used Loaded event.
A less trivial way to do it is to declare it in XAML like this:

<Window ...
    FocusManager.FocusedElement="{Binding ElementName=initiallyFocusedElement}">

The idea is taken from this blog.

I don’t think the default of setting focus on the form (or wherever it is by default) is reasonable. Normally you do want focus on the first control that may get keyboard input. I see at least three problems with no-initial-focus default:

* You need to know how to change it (took me about an hour of googling)
* You need to write the code explicitly in each and every form
* The element name may easily go out of sync and you won’t notice it until run time, or not at all, since there is no exception if the element name is incorrect

Most people won’t bother, and the result would be many forms with no initial focus, and annoyed users.

Leave a Reply

Your email address will not be published. Required fields are marked *