代码之家  ›  专栏  ›  技术社区  ›  TheZenker

用于查看消息的MVVM ViewModel

  •  4
  • TheZenker  · 技术社区  · 16 年前

    MVVM问题。 视图模型和视图之间的消息传递,如何最好地实现它?

    应用程序具有一些_用户通信_点,例如:_您已为此选择输入注释。当“是/否/不”选项的值更改时,是否要保存或放弃_。 因此,我需要一些禁止的视图绑定方式来绑定到ViewModel_S_156;messages_157;。

    我沿着MVVM基金会的信使走下了道路。然而,这更多的是一个系统范围的广播,而不是一个事件/订户模型。因此,如果应用程序有两个视图实例(person1 editview和person2 editview)打开,当一个视图模型发布“是否要保存”消息时,它们都会收到消息。

    你用了什么方法?

    谢谢 安迪

    2 回复  |  直到 16 年前
        1
  •  5
  •   Anderson Imes    16 年前

    对于所有这些,您将使用绑定作为“通信”的方法。例如,确认消息可能会根据ViewModel中设置的属性显示或隐藏。

    这是View

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

    这是你的视图模型

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

    这不是完整的样本(唯一的选择是“是”!:)),但希望这说明视图和视图模型几乎是一个实体,而不是两个互相进行电话呼叫的实体。

    希望这有帮助。

        2
  •  2
  •   Phil    16 年前

    安德森所描述的可能足以满足您所描述的特定需求。但是,您可能希望了解 表达式混合行为 它为视图模型和视图之间的交互提供了强大的支持,这在更复杂的场景中可能很有用——对“消息”使用绑定只能达到目前为止的效果。

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

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

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

    information

    Blend SDK

    video on behaviors