Accessing a property in one ViewModel from another

If you want direct access to the list from an external ViewModel, then your options are to:

  1. Pass the List to the OtherVM as a constructor argument or public property. Then the OtherVM can treat it like a member.

  2. Pass the MainVM to the OtherVM as a constructor argument or public property. Then the OtherVM can access the List by first accessing the MainVM.

Example:

public class MainVM
{
    public List<XX> MyList { get; set; }
}

public class OtherVM
{
    public MainVM TheMainVM { get; set; }

    public OtherVM(MainVM theMainVM)
    {
        TheMainVM = theMainVM;
        
        // Access the MainVM's list 
        TheMainVM.MyList.Add(stuff);            
    }
}
  1. Give the MainVM a static property called “Default” or “Instance,” so you can access the static instance of MainVM from within OtherVM, without assigning it as a member field.

Example:

public class MainVM
{
    private static MainVM _instance = new MainVM();
    public static MainVM Instance { get { return _instance; } }

    public List<XX> MyList { get; set; }
    //other stuff here
}

//From within OtherVM:
MainVM.Instance.MyList.Add(stuff);

Leave a Comment