tags:

views:

413

answers:

3

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?

+1  A: 

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.

Botz3000
I agree. Since the issue is really a visual thing in the UI, it seems it should be in the View. To me Xaml IS code, just really hard to read... A little code in the View to select some text, hidden behind some interface that can be mocked, or some event seems fine compared to trying to rig-up a dependency property. Having focus and selectalltext properties in the ViewModel seems backwards as these things don't give a 'view of the model' at all. Too many hoops to just through and more confusion wrt to separation of responsibilities.
deep108
A: 

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.