1

I have a page and a popup page.

public partial class PageA
{
    public PageAViewModel vm;

    public PageA()
    {
        BindingContext = vm = new PageAViewModel();
        InitializeComponent();
    }

public partial class PageAViewModel
{
    public int Field1;
    public int Field2;
    public int Field3;

    public async Task OpenPopup()
    {
        PopupA popup = new PopupA();
        await PopupNavigation.Instance.PushAsync(popup);
    }

    public void Method1() { }:

And

public partial class PopupA
{
    public PopupViewModel vm;

    public PopupA()
    {
        BindingContext = vm = new PopupViewModel();
        InitializeComponent();
    }

public partial class PopupViewModel
{
    // How can I get the value of Field1, Field2 and Field3 here? 
    // How can I call Method1 here?
Alan2
  • 23,493
  • 79
  • 256
  • 450

2 Answers2

1

pass a reference to the VM when creating the popup

PopupA popup = new PopupA(this);

then in PopupA

public PopupA(PageAViewModel vma)
{
    BindingContext = vm = new PopupViewModel(vma);
    InitializeComponent();
}

then in PopupViewModel

public PopupViewModel(PageAViewModel vma)
{
    // now this VM has a reference to PageAViewModel
}

note that this is not a great design approach and it is deeply coupling these two classes

Jason
  • 86,222
  • 15
  • 131
  • 146
  • Can you elaborate a bit more. What I am trying to do is to give PopupViewModel a reference to the PageAViewmodel's fields and methods. – Alan2 Dec 12 '20 at 12:28
  • I agree with your comments about the coupling. Do you have any suggestion on how this could be solved? – Alan2 Dec 12 '20 at 12:53
  • Can you please check this line. I believe you mean I should pass a reference to the ViewModel but here you suggest passing a page reference. – Alan2 Dec 12 '20 at 13:18
  • if the code **you** posted the line `PopupA popup = new PopupA();` is contained in `PageAViewModel` – Jason Dec 12 '20 at 14:39
1

You can do this by adding a design pattern in your project . I use MVVM Light and in that I add a ViewModelLocator class to create a singleton pattern.

https://www.c-sharpcorner.com/article/xamarin-forms-mvvm-viewmodel-locator-using-mvvm-light/

Following the link and then you can write

var xyz = App.ViewModelLocator.YourViewModel.YourPublicProperty;
Shubham Tyagi
  • 798
  • 6
  • 21
  • Are you using MVVM Light for every ViewModel in your project. How about the simple case where BindingContext = vm = new PageAViewModel(); works. Is there any advantage in using MVVM light for this? – Alan2 Dec 12 '20 at 13:22
  • the advantage is your code management there is no coding ethic violation in using singleton pattern as opposed to the other answer which is sort of a fix rather than a solution which is scalable, modular and robust. https://stackoverflow.com/questions/5462040/what-is-a-viewmodellocator-and-what-are-its-pros-cons-compared-to-datatemplates – Shubham Tyagi Dec 12 '20 at 14:22