2009-12-30 65 views
4

MVVM問題。 ViewModel和View之間的消息傳遞如何最好地實現?MVVM ViewModel查看消息傳送

該應用程序具有「用戶通信」的一些要點,例如:「您已爲此選擇輸入註釋。當「是/否」/「不適用」選擇的值發生變化時,您希望保存還是放棄「。 所以我需要一些被禁止的視圖綁定到ViewModel的「消息」。

我從MVVM基金會的Messenger開始走下了路徑。然而,這更像是全系統廣播,然後是事件/訂戶模型。因此,如果應用程序有兩個View實例(Person1 EditView和Person2 EditView)打開,它們都會在一個ViewModel發佈「您要保存」消息時獲取消息。

你用什麼方法?

感謝 安迪

回答

5

對於這一切,你會使用綁定作爲方法「通信」。例如,確認消息可能會根據ViewModel中設置的屬性顯示或隱藏。

這裏是查看

<Window.Resources> 
    <BoolToVisibilityConverter x:key="boolToVis" /> 
</Window.Resources> 
<Grid> 

<TextBox Text="{Binding Comment, Mode=TwoWay}" /> 
<TextBlock Visibility="{Binding IsCommentConfirmationShown, 
         Converter={StaticResource boolToVis}" 
      Text="Are you sure you want to cancel?" /> 

<Button Command="CancelCommand" Text="{Binding CancelButtonText}" /> 
</Grid> 

,這是你的ViewModel

// for some base ViewModel you've created that implements INotifyPropertyChanged 
public MyViewModel : ViewModel 
{ 
    //All props trigger property changed notification 
    //I've ommited the code for doing so for brevity 
    public string Comment { ... } 
    public string CancelButtonText { ... } 
    public bool IsCommentConfirmationShown { ... } 
    public RelayCommand CancelCommand { ... } 


    public MyViewModel() 
    { 
      CancelButtonText = "Cancel"; 
      IsCommentConfirmationShown = false; 
      CancelCommand = new RelayCommand(Cancel); 
    } 

    public void Cancel() 
    { 
      if(Comment != null && !IsCommentConfirmationShown) 
      { 
       IsCommentConfirmationShown = true; 
       CancelButtonText = "Yes"; 
      } 
      else 
      { 
       //perform cancel 
      } 
    } 
} 

這不是一個完整的示例(唯一的選擇是肯定的!:)),但希望這說明了你的視圖和你的ViewModel幾乎是一個實體,而不是兩個互相打電話。

希望這會有所幫助。

+0

是的,這是方向我期待着去。只需稍微正式化一下即可。謝謝 – TheZenker 2009-12-30 18:25:19

+0

好的...祝你好運正規化。 – 2009-12-30 18:34:10

2

安德森所描述的可能足以滿足您描述的特定要求。但是,您可能需要考慮Expression Blend Behaviors,它們爲視圖模型和視圖之間的交互提供了強大的支持,這在更復雜的場景中可能很有用 - 使用「消息」綁定只會讓您感到滿意。

請注意,表達式混合SDK可以免費使用 - 您不必使用Expression Blend來使用SDK或行爲;儘管Blend IDE對行爲的「拖放」有更好的內置支持。

此外,請注意每個「行爲」是一個組件 - 換言之,它是一個可擴展的模型; SDK中有一些內置行爲,但您可以編寫自己的行爲。

以下是一些鏈接。 (注意,不要讓在URL中的 'Silverlight的' 誤導你 - 行爲都支持WPF和Silverlight):

information

Blend SDK

video on behaviors

+0

我聽說過有關行爲但尚未調查。感謝您的提示,我會檢查出來。 – TheZenker 2010-01-04 15:02:44