我正在尝试将参数传递给子ViewModel构造函数,该构造函数抛出" MvvmCross.Platform.Exceptions.MvxException:无法构造和初始化ViewModel ... MvxIoCResolveException:无法解析MyType类型的参数myParam的参数..."
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吗?什么是最佳做法?
提前感谢你宝贵的时间。
答案 0 :(得分:4)
如果您阅读了文档 使用MvxNavigationService传递对象很容易:https://www.mvvmcross.com/documentation/fundamentals/navigation
请注意,该文档适用于目前每晚发布的MvvmCross 5.2,但5.0及以后版本几乎相同。
在您的ViewModel中,这可能如下所示:
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
}
}
答案 1 :(得分: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
}
}