Passing values ​​between Viewmodel in MVVM in WPF

I am developing a WPF application using the MVVM toolkit. I have a datagrid in my Mainwindow. I created another window called "openfile" and their viewmodels. The Main Window viewmodel class contains a public property of type ObservableCollection MyList that is associated with the Datagrid.Can. Can I populate this property from the openfile Viewmodel and automatically bind to the Datagrid? or can I pass varaible to MainViewmodel and make a public function call in MainViewmodel from OpenfileViewmodel?

This is how I call MyPage from the menu bar.

 private void NotificationMessageReceived(NotificationMessage msg)
        {
            switch (msg.Notification)
            {
                case Messages.MainVM_Notofication_ShowNewbWindow:
                    new NewView().ShowDialog();
                    break;
                case Messages.MainVM_Notofication_ShowExistingWindow:
                    new OpenExisitingView().ShowDialog();
                    break;

                case Messages.MainVM_Notofication_ShowotherWindow:
                    newView().ShowDialog();
                    break;
            }
        }

Thanks at Advance. Roshil K

+5
source share
3 answers

Mainviewmodel .

MainViewModel mainViewModelInstaince = ServiceLocator.Current.GetInstance<MainViewModel>();

.. .

..

+3

- MainWindowViewModel OpenFileViewModel:

public class OpenFileViewModel
{
    private MainWindowViewModel _parent;

    public OpenFileViewModel(MainWindowViewModel parent)
    {
          _parent = parent;
    }
}

/ / MainWindowViewModel:

foreach (var item in _parent.myList)
{
    ...
}
+1

You can create a class that can be your Mediation Service, and it will be between your ViewModels projections. You can register your broker service and add events that you can raise from one virtual machine and process in another. It could be like:

public class MediatorService: IMediatorService 
{
  public dynamic Data { get; set;}
  public event EventHandler<YourCustomEventArgs> Callback = delegate { }
}

public class XYZVM(IMediatorService mediatorService)
{
// set your Data here and handle Callback event here and refresh your grid.
// you can get anything from your "YourCustomEventArgs" which you will set from ABCVM
}

public class ABCVM(IMediatorService mediatorService)
{
// get your data here and raise callback here and handle that in XYZVM
}

Hope this helps you.

+1
source

All Articles