Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Setting the Initial Focus in WPF

0.00/5 (No votes)
14 Apr 2010 1  
Shows how to set the initial focus in XAML

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._textSearch.Focus();
}

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

<Window ...

        Loaded="OnLoaded">

Occasionally, I also see the event being set up in the constructor. For some reason, this really gets on my nerves. I 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 :)

[1] For more information about focus scopes, see FocusManager Class on the MSDN web site.

This work is licensed under a Creative Commons Attribution By license.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here