2017-08-29 92 views
0

我试图将一个参数传递给引发“MvvmCross.Platform.Exceptions.MvxException:无法构造和初始化ViewModel的子ViewModel构造函数... MvxIoCResolveException:无法解析参数类型MyType的参数myParam ......”MVVMCROSS - 将参数传递给ViewModel

MyChildViewModel.cs

public class MyChildViewModel : MvxViewModel 
{ 
    private MyType _myParam; 
    public MyType MyParam 
    { 
     get { return _myParam; } 
     set 
     { 
      if (SetProperty(ref _myParam, value)) 
      { 
       RaisePropertyChanged(() => MyParam); 
      } 
     } 
    } 

    public MyChildViewModel(MyType myParam) 
    { 
     _myParam = myParam; 
    } 

} 

在我父母的ViewModel我有:

public ICommand ShowDialogCommand { get; private set; } 
ShowDialogCommand = new MvxCommand<MyType>(e => ShowViewModel<MyChildViewModel>(e)); 

父活动电话:

ViewModel.ShowDialogCommand.Execute(VarOfMyType); 

我明明做错了什么。这是甚至可以将数据传递给子ViewModel的远程可接受的方法吗?最佳做法是什么?

预先感谢您宝贵的时间。

回答

2

如果你的文档 上阅读起来很容易通过对象与MvxNavigationService:https://www.mvvmcross.com/documentation/fundamentals/navigation

请注意,该文档适用于MvvmCross 5.2,该版本目前处于夜间版本中,但对于5.0及更高版本而言几乎相同。

在您的视图模型,这可能是这样的:

public class MyViewModel : MvxViewModel 
{ 
    private readonly IMvxNavigationService _navigationService; 
    public MyViewModel(IMvxNavigationService navigationService) 
    { 
     _navigationService = navigationService; 
    } 

    public override void Prepare() 
    { 
     //Do anything before navigating to the view 
    } 

    public async Task SomeMethod() 
    { 
     await _navigationService.Navigate<NextViewModel, MyObject>(new MyObject()); 
    } 
} 

public class NextViewModel : MvxViewModel<MyObject> 
{ 
    public override void Prepare(MyObject parameter) 
    { 
     //Do anything before navigating to the view 
     //Save the parameter to a property if you want to use it later 
    } 

    public override async Task Initialize() 
    { 
     //Do heavy work and data loading here 
    } 
} 
+0

感谢@ Martijn00提供快速回复。你是最棒的,我爱mvvmcross!我确实在v5.0.5上。您的IMvxNavigationService示例是否按原样工作5.0?我应该注意到5.0和5.2之间有什么区别? – Stack

+0

区别在于'void Prepare(MyObject parameter)'的覆盖。在5.0这是'任务初始化(MyObject参数)',但我们改变了。 – Martijn00

+0

工作就像一个魅力。非常感谢你!儿童NextViewModel v5.0:'公共覆盖任务初始化(MyObject参数)'和'返回Task.FromResult(false);'父ViewModel - 使用'MvxAsyncCommand':'SomeMethodCommand = new MvxAsyncCommand(SomeMethod);' – Stack

2

this website他们确实是(调整和修改你的情况下)的方式:

public ICommand ShowDialogCommand { get; private set; } 
ShowDialogCommand = new MvxCommand<MyType>(ShowMyVM); 

private void ShowMyVM(MyType e) 
{ 
    if (e != null) 
     ShowViewModel<SingleClientViewModel>(e); 
    else 
    { 
     //handle case where your parameter is null 
    } 
} 
+0

试了一下。它不能解决潜在的问题,但为空检查和你的时间+1。 – Stack