0

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. i.e. 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?

Dazy Jackson
  • 85
  • 1
  • 4
  • 12
  • 1
    If you are not passing data between *ViewModels* you are missing the point of MVVM. – Jon Apr 25 '12 at 15:41

2 Answers2

0

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.

csteinmueller
  • 2,427
  • 1
  • 21
  • 32
  • yes this is exactly what I want to do. If I bind all button to their ICommand, what happen if in the future there will be another view that needs to be updated? does it mean that I need to update the Excecute method? – Dazy Jackson Apr 25 '12 at 16:42
  • As Jon says, you could register all viewmodels on an event. In the ICommand you simply raise the different events (xxxPressedEvent, NewUserEvent etc etc). If there will be anew view(model), this object simply has to register on the right events. This could be in a MenuViewModel where all events and all Execute methods are located. – csteinmueller Apr 25 '12 at 17:48
0

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.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • I sometimes use a MVVMC (C for Controller) pattern. The controller (as the name says) controls the interaction between the ViewModels. Maybe he gives every ViewModel an instance of MenuViewModel. The next step would be to use Unity to register ViewModels via eventaggregator or use a ViewModel locator (see MVVMLight). – csteinmueller Apr 25 '12 at 16:15