简体   繁体   English

在不同视图之间传递数据

[英]Passing data between different views

I am writing a WPF application in C# according to the MVVM model. 我正在根据MVVM模型用C#编写WPF应用程序。 I have a MainWindow which consists of several views: MenuView, ContentView1, ContentView2, . 我有一个MainWindow,其中包含几个视图:MenuView,ContentView1,ContentView2 、。 . . and so on. 等等。

The MenuView, ContentView1, ContentView2 . MenuView,ContentView1,ContentView2。 . ., are all cousins (not bothers) in the XAML tree. 是XAML树中的所有表亲 (不打扰)。

The MenuView consists of few buttons. MenuView由几个按钮组成。 Each button has a unique ID. 每个按钮都有一个唯一的ID。 The Content Views (all of them) should receive the menu ID of a selected (clicked) button. 内容视图(所有视图)应收到一个选定(单击)按钮的菜单ID。 ie when a button in the MenuView is clicked I want to pass its ID to ContentsViews1, ContentsViews2 and so on. 即,当单击MenuView中的按钮时,我要将其ID传递给ContentsViews1,ContentsViews2等。

I am not sure what is the best way to pass data between the views. 我不确定在视图之间传递数据的最佳方法是什么。

I thought to attach an event handler to all menu buttons which reside in the MenuView. 我想将一个事件处理程序附加到驻留在MenuView中的所有菜单按钮上。 The handler is implemented in MainWindow class (which is the root view). 该处理程序在MainWindow类(这是根视图)中实现。 This handler will raise a RoutedEvent (with tunnel option) to all children views. 该处理程序将向所有子视图引发一个RoutedEvent(带有tunnel选项)。

Is there a better way to do it? 有更好的方法吗? Is it the best way considering performance issue? 这是考虑性能问题的最佳方法吗?

This approach reminds me a little bit on my long gone java experience where you pass some kind of actionstring!? 这种方法使我想起了我久违的Java经验,您在其中传递了某种操作字符串! to the listener. 给听众。

You bind all buttons to one handler? 您将所有按钮绑定到一个处理程序? And depending on the Id, you want to perform actions inside the subviews? 并根据ID,要在子视图中执行操作?

If yes, you should bind all buttons to it's own ICommand and perform actions inside the handler delegate. 如果是,则应将所有按钮绑定到它自己的ICommand上,并在处理程序委托中执行操作。

You could simply have MenuViewModel expose an event that the other (interested) ViewModels would subscribe to. 您可以简单地让MenuViewModel公开其他(感兴趣的)ViewModel可以订阅的事件。 Each View could then bind on the corresponding event and do what it needs to do. 然后,每个视图都可以绑定到相应的事件,并执行所需的操作。

This leaves open the question of how each interested ViewModel would detect the presence of MenuViewModel so that it can subscribe to its events, but that cannot be really answered without more knowledge about your application and your MVVM framework of choice. 这就留下了一个问题,即每个感兴趣的ViewModel如何检测MenuViewModel的存在,以便它可以订阅其事件,但是如果没有更多关于您的应用程序和所选MVVM框架的知识,就无法真正回答这一问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM