0

I have a WPF-Application with MVVM and a few TextBoxes. In my ViewModel I evaluate the input of the textboxes (database query) and decide which TextBox to focus next. If the input is incorrect I want to output a MessageBox and keep the focus on the current TextBox.

My evaluation is triggered by a "LostFocus" event but I have no clue how to set the focus on a specific TextBox in ViewModel.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
manu
  • 35
  • 1
  • 2
  • Does this answer your question? [Set the focus on a textbox in xaml wpf](https://stackoverflow.com/questions/2872238/set-the-focus-on-a-textbox-in-xaml-wpf) – M.B. Jun 24 '20 at 09:28
  • When you show a messagebox, this will take focus. So you can't "keep focus on the current textbox". You would need to set focus back onto it once the user has closed the messagebox. You probably want to reconsider use of a modal dialog and use some other mechanism within the parent view. Like a tooltip or something which won't take focus. I usually have a user message textblock I output all messages to. – Andy Jun 24 '20 at 10:08
  • Tanks, I dont have to show a MessageBox but i really have to know how to set the focus on a TextBox from the ViewModel, thats my main concern. – manu Jun 24 '20 at 11:33
  • @manu: So how does the view model know which TextBox to focus? Why does it know about any `TextBox` at all? – mm8 Jun 24 '20 at 14:39

1 Answers1

0

As the view model should not reference the view, i would approach this via an event. Declare an event on the view model which is raised when the focus should happen. The event args can contain information about which TextBox is supposed to be focused.

You then need to handle the event in the view where you can get a reference to your TextBox. How exactly this happens depends on your exact code and binding mechanism. If you have a view-model-first approach, you can already access the view model in the view constructor and subscribe to the event there.

If you want to avoid code-behind in the view you will have to use markup extensions or attached properties, which i would probably not consider to be worth the effort.

H.B.
  • 166,899
  • 29
  • 327
  • 400