Fresh
Fresh

Reputation: 183

WPF MVVM Pattern, need to send objects from one viewmodel to another one

Hi I have 3 ObservableCollections of a custom type in Viewmodel lets call it ViewmodelA and I need to send those collections to ViewmodelB. I tried to register a method that returns a List of the 3 ObservableCollections using MessengerInstance but it is complaining that it is expecting a return type of void.

Keeping the mvvm pattern in mind what would be the best way of getting these colllections over to ViewModelB?

Btw I am using mvvm-light

this is the method i made to return the lists:

private List<ObservableCollection<Column>> RetrieveFilters(Column col)
{
    List<ObservableCollection<Column>> Out = new     List<ObservableCollection<Column>>
    {
        _manuColumns,
        _pnColumns,
        _nounModColumns
    };

    return Out;
}

then I tried to register the method with

 MessengerInstance.Register<Column>(this, RetrieveFilters);

the error I get is

List<ObservableCollection<Column>> PropertyViewModel.RetrieveFilters(Column) has the wrong return type

Upvotes: 0

Views: 1194

Answers (1)

Boo
Boo

Reputation: 673

your messenger approach is good, if you are using mvvm light , you should implement like this

class MyMessage
 {

      ObservableCollections col1 {get;set;}
      ObservableCollections col2 {get;set;}
      ObservableCollections col3 {get;set;}

    public MyMessage(ObservableCollections col1, ObservableCollections col2, ObservableCollections col3)
    {
       this.Col1 = col1;
       this.Col2 = col2;
       this.Col3 = col3;
     }
 }

class viewmodelA
 {
    void someFunc()
     {
       Messenger.Default.Send(new MyMessage (collection1, collection2, collection3);
     }
 }

class viewmodelB
 {
      viewmodelB()
      {
        Messenger.Default.Register<MyMessage > (this, message => DoSomething(message);
      }

      public void DoSomething(MyMessage message)
         {
             //use your collections
          }
 } 

Upvotes: 2

Related Questions