Question

I'm experimenting with MVVM in the context of a simple WPF app. I have a Command attached to a button. If the text in a TextBox is 'incorrect', I want the TextBox to get focus and all it's contents selected. It seems the only way to do this is either through some kind of direct call from the Command in my ViewModel to the View, or setup some kind of Event that the ViewModel fires and the View listens for. From there the view can make direct calls on the TextBox in question.

I'm trying to stay within the decoupled nature of MVVM, but it seems like there's no way I can get this behavior declaratively in XAML, or in code directly in the ViewModel without at least indirectly talking to the View (either an interface or eventing). I'd also have to hold a reference to the View in the ViewModel.

What would be considered a 'best practice' here, and how decoupled are Views really supposed to be from ViewModels in 'real' MVVM applications?

Was it helpful?

Solution

It's code that is directly tied to the controls of your UI, so i think in this case the View's code-behind is where it belongs. You might want to setup an event or something like that. That way it's still as decoupled as before - the view knows of the viewmodel anyway, you just have a few more lines of code in the code-behind.

OTHER TIPS

i have encountered same problem, what i did is made a customized text box and expose dependency property from this control.

Like focus,selectalltext and bind these properties to view model.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top