views:

356

answers:

2

Using Silverlight 4.

I have two visual states for my control. I want to change the focus from one textbox to another when the states change.

What is the best way to do this using MVVM?

I was hoping to use the visualstatemanager to do it or a behavior... but I have not figured out a way.

A: 

Changing the focus between text boxes is most definitely view-specific code so I think it should probably be done in the code behind of the view. Some people suggest having no code at all but I think that's a bit of an exaggeration.

As for how to trigger it from the ViewModel, I would do something like:

class MyView : UserControl {

    // gets or sets the viewmodel attached to the view
    public MyViewModel ViewModel {
        get {...}
        set {
           // ... whatever method you're using for attaching the
           // viewmodel to a view
           myViewModel = value;
           myViewModel.PropertyChanged += ViewModel_PropertyChanged;
    }

    private void ViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) {
        if (e.PropertyName == "State") {
            VisualStateManager.GoToState(this, ViewModel.State, true);
            if (ViewModel.State == "FirstState") {
                textBox1.Focus();
            }
            else if (ViewModel.State == "SecondState") {
                textBox2.Focus();
            }
        }
    }

}

class MyViewModel : INotifyPropertyChanged {

    // gets the current state of the viewmodel
    public string State {
        get { ... }
        private set { ... } // with PropertyChanged event
    }

    // replace this method with whatever triggers your
    // state change, such as a command handler
    public void ToggleState() {
        if (State == "SecondState") { State = "FirstState"; }
        else { State = "SecondState"; }
    }

}
Josh Einstein
+1  A: 

If I were you I'd create a FocusBehaviour, with a FocusBehavior.IsFocused property, add that Behaviour on your Control and in the VSM state set IsFocused=True.

JustinAngel