I have a View that has a single TextBox
and a couple Button
s 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With