Error passing parameters to mvvmcross viewmodels

2019-08-06 12:34发布

问题:

I found this example in the Bestseller exmaple

public ICommand ViewDetailCommand
{
    get { return new MvxRelayCommand(() => RequestNavigate<BookViewModel>(new { category= CategoryEncoded, book=ISBN })); }
}

public BookViewModel(string category = null, string book = null)
{
    category = category ?? string.Empty;
    book = book ?? string.Empty;

    AsyncFindBook(category, book);
 }

So I have tried doing

public IMvxCommand GetGpsCommand
{
    get
    {
        return new MvxRelayCommand<SetupViewModel>(type => RequestNavigate<GpsViewModel>(new {installedMeter = _installedMeter}));
    }
}

public GpsViewModel(InstalledMeter installedMeter = null)
{
    _installedMeter = installedMeter;

    Latitude = 0.0;
    Longitude = 0.0;
    ButtonStartReading = "Start";

    this.GetService<IGpsService>().CoordinatesFoundEvent += CoordinatesFound;
    //this.GetService<IGpsService>().StartReading();
}

But when I try this I just get

Cirrious.MvvmCross.Exceptions.MvxException: Failed to load ViewModel for type Core.ViewModels.InstallUnit.GpsViewModel from locator MvxDefaultVi…

回答1:

Update: this answer is no longer up-to-date for MvvmCross

MvvmCross now supports ints, longs, enums, doubles and strings. Further, you can navigate by your own serializable types using the advice on: http://slodge.blogspot.co.uk/2013/01/navigating-between-viewmodels-by-more.html


Original answer:


This is an error that is often encountered.

MvvmCross navigation parameters must be strings

The reason for this is because the navigation itself needs to be serialized to a Xaml Url on WP7/8 and to an Intent on Android.

For more info, see:

  • Passing on variables from ViewModel to another View (MVVMCross)

and

  • Constructor in ViewModel

For more frequent navigation problems, check out the Navigation section on: http://slodge.blogspot.co.uk/p/mvvmcross-quicklist.html

If you believe more types should be supported then there is an open issue request - https://github.com/slodge/MvvmCross/issues/45


For small data-only objects, you can serialize them to text and pass them through this constructor mechanism. The only limits really are the size limits placed on Xaml Urls (these can get quite small).

However, for most cases, I would expect that viewModel-viewModel navigation will pass some kind of lookup key - using to a persistent-service. MvvmCross can help with the navigation, but it the app developer needs to understand the lifecycle of each app within its OS.



标签: c# mvvmcross