2009-12-30 35 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