Navigating to ViewModel Outside of MvxViewModel Context






4.56/5 (4 votes)
This tip will explain how to perform a navigation to ViewModel outside MvxViewModel context on MvvmCross platform.
MvvmCross Navigation Using IMvxViewDispatcher
If you are familiar with mvvmcross platform, you probably know that there is nothing simpler then making a navigation from one viewmodel to another by simply calling ShowViewModel
method that you get out of the box.
However, sometimes, you need to perform this kind of navigation outside the viewmodel.
Lucky us, we got an interface called IMvxViewDispatcher
, which can be resolved using MvvmCross dependency injection.
Navigation
private void ShowViewModel<T>()
{
var dispatcher = Mvx.Resolve<IMvxViewDispatcher>()
dispatcher.ShowViewModel(new Cirrious.MvvmCross.ViewModels
.MvxViewModelRequest(typeof(T), null, null, null));
}
Passing Parameters to ViewModel
You can pass parameters to viewmodel using MvxBundle
object and receive them in InitFromBundle
method.
//Creating parameters
Dictionary<string, string> bundle = new Dictionary<string, string>();
bundle.Add("some-key","some-value");
//Calling the method with bundle
ShowViewModel<SomeViewModelOfYours>(bundle);
private void ShowViewModel<T>(object param = null)
{
MvxBundle bundle = null;
if (param != null)
{
//Creating MvxBundle from dictionary
bundle = new MvxBundle(param.ToSimplePropertyDictionary());
}
var dispatcher = Mvx.Resolve<IMvxViewDispatcher>();
dispatcher.ShowViewModel(new Cirrious.MvvmCross.ViewModels
.MvxViewModelRequest(typeof(T), bundle, null,null));
}