casillas
casillas

Reputation: 16813

Passing Parameter From Main to Detail in MVVMCross

I am trying to pass the selected item from the list to the detail view, but myitem is null in the DetailViewmodel even though it is not in the MyViewModel.

MyViewModel.cs

    public virtual ICommand ItemSelected
    {
        get
        {
            return new MvxCommand<MyViewModel>(item =>{SelectedItem = item;});
        }
     }

    public MyViewModel SelectedItem
    {
        get { return _selectedItem; }
        set
        {
            _selectedItem = value;
            // myItem is NOT null here!!!
            ShowViewModel<MyDetailViewModel>(new { date = Date, myItem = _selectedItem });
            RaisePropertyChanged(() => SelectedItem);
        }
    }

MyDetailViewModel.cs

public class  MyDetailViewModel: MvxViewModel
{
    private MyViewModel _myItem;

    public void Init(DateTime date, MyViewModel myItem = null)
    {
        // myItem is NULL here!!!
        _myItem = myItem;
    }
}

Upvotes: 1

Views: 2203

Answers (2)

Sven-Michael St&#252;be
Sven-Michael St&#252;be

Reputation: 14760

You can use a parameter object, because you can only pass one parameter. I usually crate a nested class Parameter for this.

public class  MyDetailViewModel: MvxViewModel
{
    private MyViewModel _myItem;

    public class Parameter
    {
        public DateTime Date {get; set; }
        public string Name {get; set;}
    }

    public void Init(Parameter param)
    {
        Name = param.Name;
    }
}

and show the viewmodel like:

ShowViewModel<MyDetailViewModel>(new MyDetailViewModel.Parameter { Date = Date, Name = _selectedItem.Name });

But be aware!

The paramters cannot be complex due certain platform issues. You might have to pass only the Id of your Item within the Parameter object and then load MyItem in your Init function. Or you pass only a string and use serialization: https://stackoverflow.com/a/19059938/1489968

Upvotes: 4

Giorgi
Giorgi

Reputation: 30883

myItem is null because if you pass typed parameter to Init it should be the only parameter you pass. According to MvvmCross ViewModel Creation documentation:

Init() can come in several flavors:.

  • individual simply-Typed parameters
  • a single Typed parameter object with simply-Typed properties
  • as InitFromBundle() with an IMvxBundle parameter - this last flavor is always supported via the IMvxViewModel interface.

Upvotes: 1

Related Questions