1

使用 Silverlight 4。

我有两种视觉状态可供控制。当状态发生变化时,我想将焦点从一个文本框更改为另一个文本框。

使用 MVVM 执行此操作的最佳方法是什么?

我希望使用visualstatemanager来做它或行为......但我还没有想出办法。

4

3 回答 3

4

如果我是你,我会创建一个具有 FocusBehavior.IsFocused 属性的 FocusBehaviour,将该行为添加到控件上并在 VSM 状态集 IsFocused=True 中。

于 2010-04-22T16:37:36.663 回答
1

更改文本框之间的焦点绝对是特定于视图的代码,所以我认为它可能应该在视图后面的代码中完成。有些人建议根本没有代码,但我认为这有点夸张。

至于如何从 ViewModel 触发它,我会这样做:

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"; }
    }

}
于 2010-04-22T13:53:14.630 回答
0

The solution from the C#er blog is pretty similar to JustinAngle's answer but I figured since it is a Silverlight specific solution it bears mentioning. Basically Jeremy Likeness creates a dummy control that he calls FocusHelper that behaves very much like FocusBehavior.

于 2013-02-18T04:27:30.270 回答