Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF MVVM Focus Field on Load

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.

like image 978
Shaun Bowe Avatar asked Jul 24 '09 15:07

Shaun Bowe


1 Answers

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.

like image 199
Anderson Imes Avatar answered Sep 17 '22 20:09

Anderson Imes