Stack
Stack

Reputation: 348

MVVMCROSS - Pass a parameter to a ViewModel

I am trying to pass a parameter to a child ViewModel constructor which throws "MvvmCross.Platform.Exceptions.MvxException: Failed to construct and initialize ViewModel ... MvxIoCResolveException: Failed to resolve parameter for parameter myParam of type MyType..."

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

}

In my parent ViewModel I have:

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

Parent activity call:

ViewModel.ShowDialogCommand.Execute(VarOfMyType);

I am obviously doing something wrong. Is this even remotely acceptable approach to pass data to a child ViewModel? What's the best practice?

Thank you in advance for your valuable time.

Upvotes: 2

Views: 5411

Answers (2)

Martijn00
Martijn00

Reputation: 3559

If you read up on the documentation it is easy to pass object with the MvxNavigationService: https://www.mvvmcross.com/documentation/fundamentals/navigation

Note that the documentation is for MvvmCross 5.2 which is currently in a nightly release, but almost the same works for 5.0 and onwards.

In your ViewModel this could look like:

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

Upvotes: 7

Keyur PATEL
Keyur PATEL

Reputation: 2329

From this website the way they did it is (adapted and modified for your case):

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

Upvotes: 2

Related Questions