4

MVVM 问题。ViewModel 和 View 之间的消息传递,如何最好地实现?

该应用程序有一些“用户交流”点,例如:“您已为此选择输入评论。当 Yes/No/NA 选择的值发生变化时,您希望保存还是丢弃”。所以我需要一些禁止视图绑定到 ViewModel 的“消息”的方式。

我从 MVVM Foundation 的 Messenger 开始。然而,这更多的是系统范围的广播,而不是事件/订阅者模型。因此,如果应用程序打开了两个视图实例(Person1 EditView 和 Person2 EditView),那么当一个 ViewModel 发布“你想保存”消息时,它们都会收到消息。

你用了什么方法?

谢谢安迪

4

2 回答 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 几乎是一个实体,而不是两个互相打电话的实体。

希望这可以帮助。

于 2009-12-30T18:18:52.687 回答
2

安德森描述的内容可能足以满足您描述的特定要求。但是,您可能希望查看为视图模型和视图之间的交互提供强大支持的Expression Blend Behaviors,这在更复杂的场景中可能很有用 - 使用“消息”绑定只会让您到目前为止。

请注意,表达式混合 SDK 是免费提供的——您不必使用表达式混合来使用 SDK 或行为;尽管 Blend IDE 确实对“拖放”行为有更好的内置支持。

另外,请注意每个“行为”都是一个组件——换句话说,它是一个可扩展的模型;SDK 中有一些内置行为,但您可以编写自己的行为。

这里有一些链接。(注意,不要让 URL 中的“silverlight”误导您 - WPF 和 Silverlight 都支持行为):

信息

混合 SDK

行为视频

于 2010-01-03T20:53:39.300 回答