Passing parameters to View Models in MvvmCross

So, today I needed to pass some information to a ViewModel in my MvvmCross application.

What I actually wanted to achieve was putting focus back the the user field in my login page, and after a few attempts I ended up simply calling ShowViewModel again in my Command method

        private async Task LoginCommand()
        {
            if (await _loginService.Login(LoginId, Pin))
            {
                ShowViewModel<HomeViewModel>(new { });
            }
            else
            {
                ShowViewModel<LoginViewModel>(new { error = "Login failed, please try again." });
            }
        }

Which meant I needed to pick up that error value in the view model, so I could tell the user that something wasn’t quite right.

It’s as simple as overriding InitFromBundle …

        protected override void InitFromBundle(IMvxBundle parameters)
        {
            base.InitFromBundle(parameters);
            if (parameters.Data.ContainsKey("error"))
            {
                Error = parameters.Data["error"];
            }
        }

Hope that helps!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s