P.N.V.KRISHNA MOHAN
P.N.V.KRISHNA MOHAN

Reputation: 1

WPF MVVM Default Focus on Textbox and selectAll

I have situation like this, I have 2 WPF forms developed using MVVM Pattern ..2nd form will be opened from first(form1 will be in backend till form2 is closed) and closing the second makes the first form active.

Now I want to make a textbox on form1 with default focus set on it. I was able to do it with FocusManager and its working fine but the same is not working fine when Im getting into form1 from form2. Also during this time I have to set the focus on the default textbox and also I need to select all the text present on it. I am unable to understand how to do this with viewmodel.

Any suggestions will be of great help for me.

Regards,

Krishna

Upvotes: 0

Views: 3229

Answers (1)

Sheridan
Sheridan

Reputation: 69979

You can focus a particular UI element using the FocusManager.FocusedElement Attached Property:

<Grid FocusManager.FocusedElement="{Binding ElementName=SomeTextBox}">
    <TextBox Name="SomeTextBox" Text="{Binding SomeProperty}" />
</Grid>

This should select the TextBox each time the view/UserControl is loaded.

As for how to select text from the view model... the solution would be the same to handle any event when using MVVM. Wrap it in an Attached Property. Please beware that it is not appropriate to handle all events in the view model, as it should not really have any knowledge of purely UI events. However, the choice is yours.

To 'wrap', or handle any event in an Attached Property, you basically declare a class that extends the DependencyObject class and define one or more static properties. Rather than go over the whole story once again, I'd prefer to direct you to my answer to the What's the best way to pass event to ViewModel? question on Stack Overflow, which provides further links and a full code example.

For background information on Attached Properties, please see the Attached Properties Overview page on MSDN.

Upvotes: 2

Related Questions