2010-04-22 74 views
1

使用Silverlight 4.MVVM visualstatemanager and focus

我有兩個視覺狀態爲我的控制。當狀態改變時,我想將焦點從一個文本框更改爲另一個文本框。

使用MVVM做到這一點的最佳方法是什麼?

我一直希望能夠使用visualstatemanager來做到這一點或行爲......但我還沒有想出一個辦法。

回答

4

如果我是你,我會創建一個FocusBehaviour,具有FocusBehavior.IsFocused屬性,添加上你的行爲控制並在VSM狀態下設置IsFocused = True。

1

更改文本框之間的焦點絕對是特定於視圖的代碼,所以我認爲它應該可以在視圖後面的代碼中完成。有人建議完全沒有代碼,但我認爲這有些誇張。

至於如何從視圖模型觸發它,我會做這樣的事情:

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

} 
0

solution from the C#er blog與JustinAngle的答案非常相似,但我認爲這是它提供的Silverlight特定解決方案。基本上Jeremy Likeness創建了一個虛擬控件,他稱FocusHelper的行爲非常像FocusBehavior。