【问题标题】:MVVM ViewModel to View MessagingMVVM ViewModel 查看消息
【发布时间】:2010-12-31 04:05:54
【问题描述】:

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

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

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

你用了什么方法?

谢谢 安迪

【问题讨论】:

    标签: wpf mvvm mvvm-foundation


    【解决方案1】:

    对于所有这些,您将使用绑定作为“通信”的方法。例如,确认消息可能会根据您在 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 几乎是一个实体,而不是两个互相打电话的实体。

    希望这会有所帮助。

    【讨论】:

    • 是的,这就是我想要的方向。只是可以将其正式化一点。谢谢
    【解决方案2】:

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

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

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

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

    information

    Blend SDK

    video on behaviors

    【讨论】:

    • 我听说过行为但尚未调查。感谢您的提示,我会检查一下。
    猜你喜欢
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多