Passing Parameter From Main to Detail in MVVMCross

六月ゝ 毕业季﹏ 提交于 2019-12-08 08:15:02

问题


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;
    }
}

回答1:


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




回答2:


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.


来源:https://stackoverflow.com/questions/36729920/passing-parameter-from-main-to-detail-in-mvvmcross

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!