WPF MVVM Focus Field on Load

Shaun Bowe picture Shaun Bowe · Jul 24, 2009 · Viewed 31.8k times · Source

I have a View that has a single TextBox and a couple Buttons below it. When the window loads I want that TextBox to have focus.

If I was not using MVVM I would just call TextBox.Focus() in the Loaded event. However my ViewModel does not know about my view so how can I accomplish this without putting code into the codebehind of my view?

EDIT: After reading the answers I decided to put this code in the view xaml

<DockPanel FocusManager.FocusedElement="{Binding ElementName=MessageTextBox}">    
    <TextBox Name="MessageTextBox" Text="{Binding Message}"/>
</DockPanel>

If this were anything other than initial page focus I would probably recommend Jon Galloway's answer since it can be controlled from the ViewModel.

Answer

Anderson Imes picture Anderson Imes · Jul 24, 2009

If it makes you feel better (it makes me feel better) you can do this in Xaml using an attached property:

http://msdn.microsoft.com/en-us/library/system.windows.input.focusmanager.focusedelement.aspx

Anything you can do in codebehind you can do in Xaml if you know the tricks. Fortunately, you didn't have to implement this trick - MS did it for you.