简体   繁体   中英

Passing data between different views

I am writing a WPF application in C# according to the MVVM model. I have a MainWindow which consists of several views: MenuView, ContentView1, ContentView2, . . . and so on.

The MenuView, ContentView1, ContentView2 . . ., are all cousins (not bothers) in the XAML tree.

The MenuView consists of few buttons. Each button has a unique ID. The Content Views (all of them) should receive the menu ID of a selected (clicked) button. ie when a button in the MenuView is clicked I want to pass its ID to ContentsViews1, ContentsViews2 and so on.

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. The handler is implemented in MainWindow class (which is the root view). This handler will raise a RoutedEvent (with tunnel option) to all children views.

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!? to the listener.

You bind all buttons to one handler? And depending on the Id, you want to perform actions inside the subviews?

If yes, you should bind all buttons to it's own ICommand and perform actions inside the handler delegate.

You could simply have MenuViewModel expose an event that the other (interested) ViewModels would subscribe to. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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