In WPF dialog boxes, I quite often see some code which looks like the following code. example.

private void OnLoaded(object sender, EventArgs e)

This is usually accompanied by some XAML that likes like the following XAML example.

<Window ...

Occasionally, I also see the event being setup up in the constructor. For some reason this really gets on my nerves. I much prefer to see event handlers defined in the XAML. I’m not quite sure what my objection is; I think I just prefer to see all the UI things in one place.

What this actually achieves (as you can probably work out), is that the control (in this case a TextBox) named _textSearch has focus when the dialog box is loaded. In actual fact, WPF provides a much easier way of setting the initial focus by using the FocusManager. The FocusManager provides a set of static methods, properties, and events that you use to determine and set the focus scope[1] and to set the focused element within the focus scope.

So, using the FocusManager, you don’t need to handle the Loaded event and manually calling the Focus method as shown in the previous code examples, you can simply set the FocusedElement on the FocusManager as shown in the following code example.

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


Simple, neat, all in one place, and no code-behind 🙂