Accessing platform specific code using IOC in MVVM Cross

By | May 11, 2016

Sometimes we need to write code specific to platform which cannot be written in View Model and needs to be accessed by the View Model. For example, you want to display a message using MessageDialog but its not possible to write the code in the View Model. In this case we can create an interface in the View Model and implement the platform specific code in the Windows 10 project.

Lets see how to do this in detail.

Step 1 : Creating Interface in the View Model

Create an IPageHelper interface in the View Model with ShowMessage method.

    public interface IPageHelper
       void ShowMessage(string message);

Step 2 : Implement the Platform Specific Code.

Create an PageHelper class implementing the MessageDialog class to display the message to the user.

    public class PageHelper : IPageHelper
        public const string AppName = "Daily Dot net Tips";

        public async void ShowMessage(string message)
                MessageDialog msg = new MessageDialog(message, AppName);
                msg.Commands.Add(new UICommand("Ok"));
                await msg.ShowAsync();

Step 3 : override the InitializeFirstChance method

Go to the SetUp.cs file and override the InitializeFirstChance method.
Register the class and interface as Singleton as shown below.

protected override void InitializeFirstChance()
Mvx.RegisterSingleton<IPageHelper>(new PageHelper());

Step 4: Invoke the Method.

That’s it. Now your class is registered as singleton and whenever required we can invoke it by resolving the interface.

var pagehelper = Mvx.Resolve<IPageHelper>();

Now you can run the app. The message dialog gets displayed.


Hope this post might have helped.

One thought on “Accessing platform specific code using IOC in MVVM Cross

  1. Pingback: Dew Drop – May 12, 2016 (#2250) | Morning Dew

Comments are closed.