Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
440 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...