MVVM中的ViewModel到View的消息传递

4
MVVM问题。ViewModel和View之间的消息传递,最佳实现方式是什么?
应用程序有一些“用户交互”点,例如:当Yes/No/NA选择的值更改时,“您已为此选择输入了评论。您要保存还是放弃”。因此,我需要一种规定的方法,将View绑定到ViewModel的“消息”。
我走过MVVM Foundation的Messenger路径。然而,那更像是一个系统范围的广播,而不是事件/订阅者模型。所以,如果应用程序有两个View(Person1 EditView和Person2 EditView)打开,当一个ViewModel发布“你想保存吗”消息时,它们都会收到消息。
你使用了哪种方法?
谢谢 安迪
2个回答

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

这并不是一个完整的示例(唯一的选项是“是”!:)),但希望这能说明您的View和ViewModel几乎是一个实体,而不是互相打电话的两个实体。
希望这可以帮助您。

是的,那正是我想要走的方向。只是可能需要稍微正式一些。谢谢。 - TheZenker

2
安德森所描述的可能已经足够满足您的特定需求。然而,您可能想了解一下Expression Blend Behaviors,它们提供了强大的支持,用于视图模型和视图之间的交互,在更复杂的情况下可能会有用 - 仅使用绑定来进行“消息”传递只能让您走得这么远。
请注意,表达式混合 SDK 可以免费获得 - 您不必使用 Expression Blend 来使用 SDK 或行为;尽管 Blend IDE 对行为的“拖放”具有更好的内置支持。
此外,请注意每个“行为”都是一个组件 - 换句话说,它是一个可扩展的模型;SDK 中有一些内置的行为,但您也可以编写自己的行为。
以下是一些链接。(请注意,URL 中的“silverlight”不要误导您 - 行为适用于 WPF 和 Silverlight): information

混合 SDK

关于行为的视频


我听说过行为(behaviors),但还没有深入研究。谢谢你的提示,我会去了解一下。 - TheZenker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接