Search code examples
c#tabsxamarin.androidandroid-viewpagermvvmcross

Passing Data from ParentViewModel to ChildViewModel


I am trying to pass data from a view model (VM) to ParentViewPagerVM to ChildTabVM. In my first VM I get the data which I want to pass to ChildTabVM. I could not find any solution how to do that.

FirstViewModel.cs

public MvxCommand GoToLocationInfoCommand
{
    get
    {
        return new MvxCommand(
            () => ShowViewModel<LocationViewPager>(new { param = "Test"}));
    }
}

ParentViewPagerViewModel.cs

public void Init(string param)
{
    Debug.WriteLine("Paramter: " + ZipCode);
}

ParentViewPagerFragment.cs

if (viewPager != null)
{
     var fragments = new List<MvxCachingFragmentStatePagerAdapter.FragmentInfo>
     {
         new MvxCachingFragmentStatePagerAdapter.FragmentInfo(
             "Tab1", typeof(Child1Fragment), typeof(Child1ViewModel)),
         new MvxCachingFragmentStatePagerAdapter.FragmentInfo(
             "Tab2", typeof(Child2Fragment), typeof(Child2ViewModel)),
         new MvxCachingFragmentStatePagerAdapter.FragmentInfo(
             "Tab3", typeof(Child3Fragment), typeof(Child3ViewModel))
     };

     viewPager.Adapter = new MvxCachingFragmentStatePagerAdapter(
         Activity, ChildFragmentManager, fragments);
}

Since I am making a tabView, I can't find a way to pass data from my ParentViewPagerVM to Child1VM. Any idea?


Solution

  • MvxCachingFragmentStatePagerAdapter.FragmentInfo constructor provides an option for passing parameters to the ViewModel type you want to have constructed.

    public FragmentInfo(
        string title, 
        Type fragmentType, 
        Type viewModelType, 
        object parameterValuesObject = null);
    

    Implementation Example

    Assuming you have a property ZipCode on your ParentViewPagerViewModel you can pass as a parameter.

    var fragments = new List<MvxCachingFragmentStatePagerAdapter.FragmentInfo>
    {
         new MvxCachingFragmentStatePagerAdapter.FragmentInfo(
             title: "Tab1", 
             fragmentType: typeof(Child1Fragment), 
             viewModel: typeof(Child1ViewModel), 
             parameterValuesObject: new { zipCode = ViewModel.ZipCode})
    };
    

    Then in your Child ViewModel retrieve it via the Init

    public void Init(int zipCode)
    {
       // Do stuff with zipCode
    }