Daniel Hindrikes
Developer and architect with focus on mobile- and cloud solutions!
Developer and architect with focus on mobile- and cloud solutions!
When I building an app with a MVVM framework I want to have my view models in a portable class library so I can use same view models for the Windows Phone app as for the iOS and Android app when building apps using Xamarin.
If I press the back button in a Windows Phone app built using MvvmCross (a MVVM framework), the app will be placed in background. That is the behavior I want if I'm on the first view of the app. But if I have navigated to Another view I would like to return to the previous view. To do that I need to handle the back button event. I want to have the code for handle the back button event in my view models that is placed in a portable class library, but the code for handling the event is platform specific. This post will show how to handle the back button event in a Windows Phone app built using WinRT. You can of course use this way to handle platform specific events for other events than the back button event.
First of all I creating an interface, I use to name it IPlatformEvents.
public interface IPlatofrmEvents
{
event EventHandler BackButtonPressed;
}
In my view models I using IoC (Inversion of Control) and constructor injection to resolve the interface. In my method for handling the back button pressed I using the Close method to close the current view and return to the previous one in the stack. Don't forget to remove the handler from the event in the handler method. If you do not, it can cause problems later.
public class MyViewModel : MvxViewModel
{
private IPlatformEvents _platformEvents;
public MyViewModel(IPlatformEvents platformEvents)
{
_platformEvents = platformEvents;
_platformEvents.BackButtonPressed += BackButtonPressed;
}
void BackButtonPressed(object sender, EventArgs e)
{
Close(this);
_platformEvents.BackButtonPressed -= BackButtonPressed;
}
}
If you want to read more about IoC and MvvmCross you can read my post about MvvmCross and IoC and my post about how to use a different IoC provider then the built-in when using MvvmCross.
Next step is to write the platform specific implementation of the interface. For an Windows Phone app using WinRT the implementation would look like this.
public class WindowsPhoneEvents : IPlatformEvents
{
public event EventHandler BackButtonPressed;
public WindowsPhoneEvents()
{
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
if(BackButtonPressed != null)
{
BackButtonPressed(this, new EventArgs());
e.Handled = true;
}
}
}
When I have created the platform specific implementation I just have to register it to the IoC container. You can read how to do it if you read the post that I linked to above.