MvvmCross – FlyoutNavigation, Hamburger Menu, Sliding Menu for Android Null Reference Exception on Fragment Shown Fix


The architecture I used in MvvmCross for a FlyoutNavigation/Hamburger Menu/Sliding Menu requires the developer to maintain ViewModel state for all of the fragments used within the menu. The original implementation did not provide such a service. On certain Android devices a null reference exception would be generated when the user navigated between fragments.

The fix described here is not a perfect solution, use with caution.

Original Articles

Source Code


After using the slide out menu architecture in an iOS, Android, and Windows Phone app I started receiving bug reports from two different Android Samsung devices.

06-09 11:36:16.740 I/MonoDroid(21351): UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object
06-09 11:36:16.740 I/MonoDroid(21351): at V.JobTrak.Apps.Droid.Views.EnterTimeView.OnCreateView (Android.Views.LayoutInflater,Android.Views.ViewGroup,Android.OS.Bundle) <IL 0x000cf, 0x00588>
06-09 11:36:16.740 I/MonoDroid(21351): at Android.Support.V4.App.Fragment.n_OnCreateView_Landroid_view_LayoutInflater_Landroid_view_ViewGroup_Landroid_os_Bundle_ (intptr,intptr,intptr,intptr,intptr) <IL 0x00026, 0x0019f>
06-09 11:36:16.740 I/MonoDroid(21351): at (wrapper dynamic-method) object.d4c53d5a-8a99-43f6-bd55-88a30287aec2 (intptr,intptr,intptr,intptr,intptr) <IL 0x00023, 0x0005f>
An unhandled exception occured.

Unhandled Exception:

Java.Lang.Throwable: Loading...

06-09 11:36:20.620 D/HockeyApp(21351): Writing unhandled exception to: /data/data/com.droid.apps.jobtrak.v/files/f6e8f1e8-532a-49e9-99e2-00970568f77a.stacktrace
06-09 11:36:20.620 E/mono-rt (21351): [ERROR] FATAL UNHANDLED EXCEPTION: Java.Lang.Throwable: Exception of type 'Java.Lang.Throwable' was thrown.
06-09 11:36:20.620 E/mono-rt (21351): at Android.Runtime.JNIEnv.NewString (string) <IL 0x0004c, 0x00260>
06-09 11:36:20.620 E/mono-rt (21351): java.lang.Throwable: System.NullReferenceException: Object referenc06-09 11:36:20.620 E/mono-rt (21351): at Android.Util.Log.Info (string,string) <IL 0x0002e, 0x00127>
06-09 11:36:20.620 E/mono-rt (21351): at Android.Runtime.AndroidEnvironment.UnhandledException (System.Exception) <IL 0x00010, 0x00093>
06-09 11:36:20.620 E/mono-rt (21351): at (wrapper dynamic-method) object.da665a14-2c2b-48b2-9db0-7303fcb7fde2 (intptr,intptr) <IL 0x00029, 0x0008f>
06-09 11:36:20.620 E/mono-rt (21351): at (wrapper native-to-managed) object.da665a14-2c2b-48b2-9db0-7303fcb7fde2 (intptr,intptr) <IL 0x0001a, 0x0006b>
06-09 11:36:20.620 E/mono-rt (21351): 
06-09 11:36:20.620 E/mono-rt (21351):   --- End of managed exception stack trace ---
06-09 11:36:20.620 E/mono-rt (21351): java.lang.Throwable: System.NullReferenceException: Object reference not set to an instance of an object
06-09 11:36:20.620 E/mono-rt (21351): at V.JobTrak.Apps.Droid.Views.EnterTimeView.OnCreateView (Android.Views.LayoutInflater,Android.Views.ViewGroup,Android.OS.Bundle) <IL 0x000cf, 0x00588>
06-09 11:36:20.620 E/mono-rt (21351): at Android.Support.V4.App.Fragment.n_OnCreateView_Landroid_view_LayoutInflater_Landroid_view_ViewGroup_Landroid_os_Bundle_ (intptr,intptr,intptr,intptr,intptr)
The program 'Mono' has exited with code 0 (0x0).

Same crash, two different devices. I couldn’t for the life of me reproduce it on my Nexus 5 and was at a loss as to what was going on.

Getting Help

I turned to StackOverflow, and almost immediately I received a response from Stuart Lodge the creator of MvvmCross.

From his answer on StackOverflow:

From your code, it looks like you are manually setting the ViewModel’s of your fragments when you first create them:

        frag.ViewModel = viewModelLocal;

Which, sure enough, that was exactly what was going on, from the HomeView.cs\Show() in the Android project:

var loaderService = Mvx.Resolve<IMvxViewModelLoader>();
var viewModelLocal = loaderService.LoadViewModel(request, null /* saved state */);
frag.ViewModel = viewModelLocal;

Bottom line, since I’ve created the ViewModel in my HomeView for a View I need to make sure it gets recreated if it is ever unloaded from memory.

Reproducing the Error with My Device

The real kicker with this issue is I could not reproduce it on my own device, or almost any other device I tested with. The error only showed up on a Samsung S3 and S5. I turned to the chat room for MvvmCross,, for advice. It was Stuart Lodge who turned me onto a devious little setting in the Android Developer Options Menu called ‘Don’t Keep Activities’.


Check that box and Android will ensure that the second you navigate away from an activity it is completely dumped from memory. When I checked it on the N5 I could re-create the crashes I was seeing in the field!

Fixing the Crashes

I do not know the proper, “Ivory Tower” method to fix this particular issue. I stumbled around for a few days trying different methods to address the null reference exception, but discovered this is a non-trivial issue. From MvvmCross’ GitHub issue tracker: Setting ViewModel property on a Fragment is not Correct

var viewModelLoader = Mvx.Resolve();
fragment.ViewModel = viewModelLoader.LoadViewModel(request, null);

This is incorrect because Fragments are managed by a FragmentManager and each Fragments lifecycle is at the mercy of that manager and Android. At any time your Fragment may be destroyed and the FragmentManager’s job is to recreate it. When it gets recreated it will no longer have the ViewModel you gave it and this will cause problems in the program. This pattern works in ideal situations but will break in many others….

The issue, as of publishing this post, is still open.

Warning – This Fix is a Hack

Realizing the proper fix was currently beyond my capability I went for a fix that appears to work. Since the fix has been implemented the app no longer crashes due to this bug. Be warned, this is a hack, understand it before you use it.

Steps Taken to Fix the Issue

  1. In HomeViewModel we’ll save the ViewModels for the fragments we are creating when OnSaveInstanceState(Bundle outState) is called in hopes MvvmCross will properly save the state of our ViewModels if they are properties of the HomeViewModel
  2. In the OnCreate() method we’ll attempt to restore the ViewModel of the fragment we are about to show, and if we can’t we’ll create a new one.

Modifying HomeViewModel

In the HomeViewModel we’ll add public properties for each of the ViewModels of our fragments.

public class HomeViewModel : BaseViewModel
    //allows us to save state for Android
    public EnterTimeViewModel EnterTimeViewModelFragment;
    public CreateNewJobViewModel CreateNewJobViewModelFragment;

Creating Our Fragments

When we create our fragments we are going to add a tag to the fragment when we add it to the SupportFragmentManager. We’ll use the fragment’s title property as the tag, thus later on we can check the SupportFragmentManager using the title of the fragment to see if the fragment exists and if it has a valid ViewModel attached to it.

this.SupportFragmentManager.BeginTransaction().Replace(Resource.Id.content_frame, frag, title).Commit();

Saving Fragment State

We’ll iterate through all of the fragments in our SupportFragmentManager, grab their ViewModels and place them in our HomeViewModel with the hopes that if the HomeViewModel is removed from memory the standard MvvmCross state saving mechanisms will also save the state of our fragment’s ViewModels.

        protected override void OnSaveInstanceState(Bundle outState)

        private void SaveViewModelStates()
            //save all of the ViewModels for fragments
            var view = this.SupportFragmentManager.FindFragmentByTag("Enter Time") as EnterTimeView;
            if (null != view)
                ViewModel.EnterTimeViewModelFragment = view.ViewModel as EnterTimeViewModel;
            var view2 = this.SupportFragmentManager.FindFragmentByTag("Create New Job") as CreateNewJobView;
            if (null != view2)
                ViewModel.CreateNewJobViewModelFragment = view2.ViewModel as CreateNewJobViewModel;

Showing a Fragment

In the OnCreate() method we used to punt if we had any savedInstanceState data.

    if (null == savedInstanceState)
}// end function

Now we will attempt to restore that state.

    if (null == savedInstanceState)
        //restore viewModels if we have them
} //end of function            

/// <summary>
/// Restore view models to fragments if we have them and the fragments were created
/// </summary>
private void RestoreViewModels()
    var loaderService = Mvx.Resolve<IMvxViewModelLoader>();

    var view = this.SupportFragmentManager.FindFragmentByTag("Enter Time") as EnterTimeView;
    if (null != view && null == view.ViewModel)
        view.ViewModel = ViewModel.EnterTimeViewModelFragment ?? loaderService.LoadViewModel(new MvxViewModelRequest(typeof(EnterTimeViewModel), null, null, null), null) as EnterTimeViewModel;
    var view2 = this.SupportFragmentManager.FindFragmentByTag("Create New Job") as CreateNewJobView;
    if (null != view2 && null == view2.ViewModel)
        view2.ViewModel = ViewModel.CreateNewJobViewModelFragment ?? loaderService.LoadViewModel(new MvxViewModelRequest(typeof(CreateNewJobViewModel), null, null, null), null) as CreateNewJobViewModel;

We iterate through all of the fragments in the SupportFragmentManager checking to see if our fragment was created, and if so if the ViewModel is valid. If it is null attempt to grab it from the HomeViewModel instance we saved away, if that is also null create a new ViewModel for the fragment.


This solution is a hack, it is ugly, and in no means the proper way to account for this behavior on the Android platform. Case and point, in my testing I found often times the HomeViewModel would have a valid reference to my fragment’s ViewModels when I attempted to restore them in the RestoreViewModels(). I may just be fooling myself in my limited testing, and there is a good chance that step doesn’t do what I’m expecting it to do. However, the worst case in this situation is a new ViewModel is created for the fragment, ensuring we do not get a null reference exception when we attempt to load our fragment.

Posted in mvvmcross, xamarin

MvvmCross – FlyoutNavigation, Hamburger Menu, Sliding Menu for Android, iOS, and Windows Phone


Provide a unified architecture for a FlyoutNavigation/Hamburger Menu/Sliding Menu for Android, iOS, and Windows Phone 8 Silverlight using MvvmCross.

flyout menus

Source Code

Original Article

See – for a walkthrough of the unified architecture for iOS and Android. This article expands upon that architecture to include Windows Phone 8.0 Silverlight.

Inspiration for Windows Phone 8.0 Silverlight Implementation

I had found a few Windows Phone slide out implementations,, but attempting to tie them in with MvvmCross appeared to be a bit of a tall order, and for a while I had given up on my dream of unifying a slide out menu architecture for all three platforms.

Then I read this great article from Scott Hanselman talking about the new Xamarin.Forms where one could write all of their presentation code once, and have it natively drawn on each platform. The app used for the demo was a iOS, Android, and Windows Phone app with a slide out menu!

Source –

Astute readers will notice, James Montemagno was the inspiration for the Android slide out menu in my original article:

I took the evening and dissected the demo Xamarin.Forms app. iOS and Android implemented the familiar ‘hamburger’ in the upper left hand corner, that when pressed, would reveal other screens the user could navigate to. The Windows Phone however placed the button on the ApplicationBar, and when pushed showed a whole new page.

Inspired, I went back to Visual Studio and proceeded to provide a Windows Phone implementation of my slide out menu architecture.

Windows Phone Silverlight Implementation

As I said, this is not the traditional slide out menu for Windows Phone. If I must confess, I’m not a daily Windows Phone user, yet, but the days where I do use Windows Phone I find the slide out menu is not as prevalent on the platform as it is ingrained on iOS and Android. My slide out implementation is a “For Now” implementation, if the platform idioms change where a true slide out becomes the norm I’ll revisit the topic.


wp8 entertime

There are two major elements we need to implement for our Windows Phone solution:
1. The HomeView.xaml to hold our application menu
2. An ApplicationBar to hold our slide out menu icon on each of our root views


The HomeView.xaml holds the list of other Views we could navigate to. For this example I kept things simple, placing the items in a ListBox. Since our HomeViewModel already has

private List<MenuViewModel> menuItems;
public List<MenuViewModel> MenuItems
    get { return this.menuItems; }
    set { this.menuItems = value; this.RaisePropertyChanged(() => this.MenuItems); }

We can bind to the MenuItems in our HomeView.xaml.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <ListBox ItemsSource="{Binding MenuItems}" >
                    <StackPanel Margin="24">
                        <TextBlock Text="{Binding Title}" Tap="UIElement_OnTap" FontSize="50" ></TextBlock>


Notice the Tap=UIElement_OnTap? In HomeView.xaml.cs It leads us to:

private void UIElement_OnTap(object sender, GestureEventArgs e)
    var selectedItem = ((HomeViewModel)ViewModel).MenuItems.FirstOrDefault(x => x.Title == ((TextBlock)sender).Text);
    if (null != selectedItem)

This allows us to figure out which cell the user pressed so we can navigate to the requested page. There are better ways to get this done, however I’m not a Windows Phone 8/MvvmCross master so I settled on this implementation for now.

Show the First View on Application Start

The only item left in our HomeView.xaml.cs is to navigate to the first view we would like our user to see when they launch the app. We accomplish that in the OnNavigatedTo

protected override void OnNavigatedTo(NavigationEventArgs e)
    if (null == ViewModel)

        var selectedItem = ((HomeViewModel)ViewModel).MenuItems.FirstOrDefault(x => x.Title == "Enter Time");
        if (null != selectedItem)

In OnNavigatedTo I am guaranteed I’ll have a valid HomeViewModel from which I can navigate to our first view, Enter Time.

Navigating Back to the Menu

From EnterTimeView we can get back to our menu two different ways:
1. Press the phone Back button
2. Press the Menu icon in the ApplicationBar

Setting Up the Phone Back Button

We actually don’t have to provide any code for this functionality, this is built into Windows Phone 8.

ApplicationBar Setup

First we’ll add the code for our ApplicationBar to EnterTimeView.xaml

    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
        <shell:ApplicationBarIconButton Click="ShowMenu" IconUri="/Toolkit.Content/ApplicationBar.Select.png" Text="Menu"/>           
        <shell:ApplicationBarIconButton Click="AddNewHoursEntry"  IconUri="/Assets/AppBar/add.png" Text="Add Hours"/>
            <shell:ApplicationBarMenuItem Click="ShowMenu" Text="Menu"/>                
            <shell:ApplicationBarMenuItem Click="AddNewHoursEntry" Text="Add Hours Entry"/>

Here I’ve added a second ApplicationBarIconButton and ApplicationBarMenuItem that would allow us to show another View when pressed to mimic the functionality in the iOS and Android implementations.

wp8 entertime app bar

Getting ApplicaitonBar.Select.png

ApplicationBar.Select.png is part of the Windows Phone Toolkit, add it to your project via NuGet if you’d like to use the same icon I’m using. Mark the icon as Content to ensure it is include with your application.


The ShowMenu() function uses the NavigationService allowing us to navigate back to our menu in the HomeView.

private void ShowMenu(object sender, EventArgs e)


The lack of slide out menus in Windows Phone 8 shouldn’t stop us from creating a Windows Phone 8 app that uses ViewModels that were designed with the slide out menu architecture in mind. With the example code one can now create one .Core MvvmCross project based on slide out menus and use it in Windows Phone 8, iOS, and Android apps.

Grab the code and try it out:

Posted in mvvmcross, xamarin Tagged with: , , , ,

MvvmCross – Keychain Plugin with Windows Phone 8 Silverlight Support


Unified MvvmCross Keychain Plugin for iOS, Android, and Windows Phone 8 Silverlight

Source Code

Original –
Updated with Windows Phone Support –


The major app platforms, iOS, Android, and Windows Phone have mechanisms available to the app developer to store usernames and passwords. The rub is, each implementation is a bit different, and none of the major frameworks have plugins for MvvmCross.

Artur Rybak went out and created a unifying plugin for MvvmCross, IHS.MvvmCross.Plugins.Keychain. I have added onto the plugin to include support for Windows 8 Silverlight applications.


Most of the time developers would never store raw usernames and passwords in their app, one strives to store a token or hash of these sensitive items. If the device is compromised the attacker woudn’t gain a user’s raw username or password.

However, when connecting to web services often times an app developer will need the raw username and password, hence each of the major platforms provide a secure system to store these credentials.


Artur Rybak‘s plugin, IHS.MvvmCross.Plugins.Keychain covers iOS and Android with a simple interface that met all of my needs:

namespace IHS.MvvmCross.Plugins.Keychain
    public interface IKeychain
        bool SetPassword(string password, string serviceName, string account);
        string GetPassword(string serviceName, string account);
        bool DeletePassword(string serviceName, string account);
        LoginDetails GetLoginDetails(string serviceName);
        bool DeleteAccount(string serviceName, string account);

The implementation uses the idea of a serviceName so one can keep their usernames/passwords separate from other services on the device.


This is a great plugin because “it just works.” Need a user name and password from your MvvmCross application?

var keyChain = Mvx.Resolve<IKeychain>();
var user = keyChain.GetLoginDetails(SERVICE);

if(null != user)
    var loginResult = service.Login(user.Username, user.Password);

keyChain.GetLoginDetails(SERVICE) will return null if a username and password cannot be found for your service.


The only issue I had was on iOS, and this may have only been a simulator issue, but I found when I attempted to update a username and/or password for a service the old entries were never deleted. To work around this issue I cleared out all user names and passwords for my particular service before adding one back in.

var keyChain = Mvx.Resolve<IKeychain>();
var user = keyChain.GetLoginDetails(SERVICE);
while (user != null) //clear out old user, if we don't it will hold onto all of the old users
    keyChain.DeletePassword(SERVICE, user.Password);
    keyChain.DeleteAccount(SERVICE, user.Username);
    user = keyChain.GetLoginDetails(SERVICE);
keyChain.SetPassword(Password, SERVICE, Username);

Windows Phone 8 Silverlight Implementation

In iOS and Android it appears there is a single system wide service that handles storage of raw passwords and usernames, and hence the required serviceName when accessing the keychain.

In Windows Phone 8 Silverlight, this isn’t the case. The best suggestion I found for storing usernames and passwords was to place them in isolated storage. I based my implementation on an answer found on StackOverflow, Username and Password data Windows phone 8 app.

public bool SetPassword(string password, string serviceName, string account)
    // Convert the password to a byte[].
    var passwordByte = Encoding.UTF8.GetBytes(password);

    // Encrypt the password by using the Protect() method.
    var protectedPasswordByte = ProtectedData.Protect(passwordByte, null);

    // Store the encrypted password in isolated storage.
    WriteToFile(protectedPasswordByte, serviceName + account);

    // same steps for the username
    var usernameByte = Encoding.UTF8.GetBytes(account);
    var protectedUsernameByte = ProtectedData.Protect(usernameByte, null);
    WriteToFile(protectedUsernameByte, serviceName);

    return true;

/// <summary>
/// Write a string to isolated storage
/// </summary>
/// <param name="data"></param>
/// <param name="filePath"></param>
private void WriteToFile(byte[] data, string filePath)
    // Create a file in the application's isolated storage.
    IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
    IsolatedStorageFileStream writestream = new IsolatedStorageFileStream(filePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, file);

    // Write pinData to the file.
    Stream writer = new StreamWriter(writestream).BaseStream;
    writer.Write(data, 0, data.Length);

Since we are storing files to isolated storage I named the password file serviceName + account and the username file just serviceName.

Obtaining a username and password requires one to read the files from isolated storage:

public string GetPassword(string serviceName, string account)
    return ReadIsolatedStorage(serviceName+account);

public string GetUsername(string serviceName)
    return ReadIsolatedStorage(serviceName);

/// <summary>
/// Given a filename read the item from isolated storage
/// </summary>
/// <param name="filename">defines item developer is looking for in isolated storage</param>
/// <returns>value found in isolated storage</returns>
private string ReadIsolatedStorage(string filename)
    using (var folder = IsolatedStorageFile.GetUserStoreForApplication())
        string returnValue = null; //null if not found
        if (folder.FileExists(filename))
            // Retrieve the item from isolated storage.
            byte[] protectedItemByte = this.ReadFromFile(filename);

            // Decrypt the item by using the Unprotect method.
            byte[] itemByte = ProtectedData.Unprotect(protectedItemByte, null);

            // Convert the password from byte to string and display it in the text box.
            returnValue = Encoding.UTF8.GetString(itemByte, 0, itemByte.Length);
        return returnValue;

/// <summary>
/// Read value from isolated storage
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private byte[] ReadFromFile(string filePath)
    // Access the file in the application's isolated storage.
    IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
    IsolatedStorageFileStream readstream = new IsolatedStorageFileStream(filePath, System.IO.FileMode.Open, FileAccess.Read, file);

    // Read the PIN from the file.
    Stream reader = new StreamReader(readstream).BaseStream;
    byte[] pinArray = new byte[reader.Length];

    reader.Read(pinArray, 0, pinArray.Length);

    return pinArray;

Windows Phone 8.1

Windows Phone 8.1 supports the Credential Locker. Once Windows Phone 8.1 is released I’ll update the library accordingly.

MvvmCross Plugin

Creating a plugin for MvvmCross was straightforward, I followed the path set by Artur Rybak, I added a KeychainPluginBootstrap.cs.pp and modified the IHS.MvvmCross.Plugins.Keychain.nuspec so the Windows Phone implementation was included in the NuGet package.

Using My Branch in a MvvmCross Application

IHS.MvvmCross.Plugins.Keychain is published on NuGet. As of publishing this blog post I have submitted a pull request to Artur Rybak to include my latest changes. If you are impatient for an ‘official release’ here are the steps you’ll need to take to get the plugin installed in your MvvmCross application.

  1. Pull down a copy of
  2. Build
  3. Drop to the command line and navigate to the common folder of IHS.MvvmCross.Plugins.Keychain.
  4. Package the plugin – nuget pack IHS.MvvmCross.Plugins.Keychain.nuspec, one should now have a new NuGet package with the Keychain plugin for iOS, Android, and Windows Phone.
  5. Open your MvvmCross project and setup Visual Studio to have a new, local NuGet repository. Tools\Options\NuGetPackage Manager\Package Sources
  6. Add the directory where you just built the NuGet Packages. I called my new local location Keychain.
    Screen Shot 2014-06-22 at 1.57.12 PM
  7. Open your MvvmCross application, Manage NuGet Packages and select the keychain package from your new local NuGet repository.
    Screen Shot 2014-06-22 at 1.58.45 PM


If one must store username’s and passwords locally on the device ensure you are using a built in mechanism to do so, attempting to create your own password store is a difficult path I do not recommend. provides a plugin for MvvmCross to work with iOS, Android, and Windows Phone.

Posted in mvvmcross, xamarin Tagged with:

MvvmCross – Xamarin.Android Popup DatePicker on EditText Click


When the user clicks on an EditText box in a MvvmCross Xamarin.Android app show a date picker popup.




All of the solutions I kept finding to this problem always had the user clicking on a button to show the DatePicker popup, and I really wanted the user to be able to show the date picker when they pressed on the EditText box, much like Android does in the default Calendar app.

From the above articles I was able to piece together a solution, the highlights:

  • Instead of setting the click event on a button set it to the EditText box.
datePickerText = view.FindViewById<EditText>(Resource.Id.DatePickerEditText);            
datePickerText.Click += delegate
    var dialog = new DatePickerDialogFragment(Activity, Convert.ToDateTime(datePickerText.Text), this);
    dialog.Show(FragmentManager, "date");
  • Ensure when the user presses on the EditText box that the system does not display the default keyboard by setting datePickerText.Focusable = false;.

  • For MvvmCross binding we only need to bind to the datePickerText.

The full solution:

public class EnterTimeView : MvxFragment, DatePickerDialog.IOnDateSetListener
    private EditText datePickerText;

    public EnterTimeView()
        this.RetainInstance = true;

    public override Android.Views.View OnCreateView(Android.Views.LayoutInflater inflater, Android.Views.ViewGroup container, Android.OS.Bundle savedInstanceState)
        this.HasOptionsMenu = true;

        var ignored = base.OnCreateView(inflater, container, savedInstanceState);
        var view = inflater.Inflate(Resource.Layout.EnterTimeView, container, false);

        datePickerText = view.FindViewById<EditText>(Resource.Id.DatePickerEditText);
        datePickerText.Focusable = false;
        datePickerText.Click += delegate
            var dialog = new DatePickerDialogFragment(Activity, Convert.ToDateTime(datePickerText.Text), this);
            dialog.Show(FragmentManager, "date");

        var set = this.CreateBindingSet<EnterTimeView, EnterTimeViewModel>();
        set.Bind(datePickerText).To(vm => vm.Date);

        return view;

    public void OnDateSet(Android.Widget.DatePicker view, int year, int monthOfYear, int dayOfMonth)
        datePickerText.Text = new DateTime(year, monthOfYear + 1, dayOfMonth).ToString();

    private class DatePickerDialogFragment : Android.Support.V4.App.DialogFragment 
        private readonly Context _context;
        private DateTime _date;
        private readonly DatePickerDialog.IOnDateSetListener _listener;

        public DatePickerDialogFragment(Context context, DateTime date, DatePickerDialog.IOnDateSetListener listener)
            _context = context;
            _date = date;
            _listener = listener;

        public override Dialog OnCreateDialog(Bundle savedState)
            var dialog = new DatePickerDialog(_context, _listener, _date.Year, _date.Month - 1, _date.Day);
            return dialog;
Posted in mvvmcross, xamarin Tagged with: ,

MvvmCross – Custom MvxTableViewCell Without a NIB File


Programmatically create a custom MvxTableViewCell without using a NIB file.

Source Code



As I venture deeper into MvvmCross based development I had a need to create a custom MvxTableViewCell without using a NIB file. There are several examples of how one can use a NIB file to complete this task, but as a general rule I try to stay away from NIB files and choose to create all of my iOS interfaces in code.

Problem Domain

I’m working on a application that allows an engineer to track their time spent against all the projects they are working on. My example user interface for this demo has a calendar with a UIDatePicker allowing the engineer to select the date and then show all of the entries they have made for that date.

iOS Simulator Screen shot Apr 16, 2014, 3.43.25 PM

My data source for this example is a simple class containing the job name, a job id, and the number of hours spent on that job:

public class EnterTime
    public string JobName { get; set; }
    public string JobId { get; set; }
    public decimal Hours { get; set; }        

Attempting to display all three elements in a standard MvxTableViewCell wasn’t working, thus the need for a custom cell.

View and ViewModel

FirstView and FirstViewModel are standard MvvmCross Views and ViewModels…no real magic needs to take place in these for us to use a custom cell. In this example code FirstViewModel provides functionality that simulates an async server call to retrieve data for a given date provided by the user. FirstViewModel is also setup for pull to refresh, delete, and select from the UITableView. Thanks again goes to James Montemagno for two great Gists to make pull to refresh and swipe to delete happen:


I used James Montemagno‘s MvvmCross TableView Swipe to Delete as a starting point for my TableViewSource and proceeded with a few key modifications.

Register Our Custom Cell Class

In the constructor we need to tell the UITableView which class we will be using for our cells, this is done via RegisterClassForCellReuse.

private IRemove viewModel;        

public MvxDeleteTableViewSource(IRemove viewModel, UITableView tableView) : base(tableView)
    this.viewModel = viewModel;
    tableView.RegisterClassForCellReuse(typeof(HoursEntryCell), new NSString("HoursEntryCell"));

Derive From MvxTableViewSource

Originally MvxDeleteTableViewSource derived from MvxStandardTableViewSource, this however caused issues with data binding failing to work for my custom cell. Deriving from MvxTableViewSource and implementing GetOrCreateCellFor solved the data binding issues.

protected override UITableViewCell GetOrCreateCellFor(UITableView tableView, NSIndexPath indexPath, object item)
    return (HoursEntryCell)tableView.DequeueReusableCell("HoursEntryCell");

Custom MvxTableViewCell

The HoursEntryCell turned out to be straight forward…in each constructor call CreateLayout and ensure data binding is initialized.

public class HoursEntryCell : MvxTableViewCell
    public HoursEntryCell()            

    public HoursEntryCell(IntPtr handle) : base(handle)

    private UILabel jobId;
    private UILabel hours;
    private UILabel jobName;

    private void CreateLayout()
        const int offsetStart = 10;
        Accessory = UITableViewCellAccessory.DisclosureIndicator;
        jobId = new UILabel(new RectangleF(offsetStart, 0, 75, 40));
        hours = new UILabel(new RectangleF(UIScreen.MainScreen.Bounds.Right - 85, 0, 55, 40));
        hours.TextAlignment = UITextAlignment.Right;
        jobName = new UILabel(new RectangleF(jobId.Frame.Right, 0, UIScreen.MainScreen.Bounds.Width - jobId.Frame.Width - hours.Frame.Width - (3 * offsetStart), 40));
        jobName.AdjustsFontSizeToFitWidth = true;
        jobName.Lines = 0;
        jobName.Font = jobName.Font.WithSize(10);
        ContentView.AddSubviews(jobId, jobName, hours);

    private void InitializeBindings()
        this.DelayBind(() =>
            var set = this.CreateBindingSet<HoursEntryCell, EnterTime>();
            set.Bind(jobId).To(vm => vm.JobId);
            set.Bind(hours).To(vm => vm.Hours);
            set.Bind(jobName).To(vm => vm.JobName);


The big hurtle I had with creating a custom UITableViewCell in MvvmCross without using a NIB file was deriving from the wrong MvxTableViewSource. Once I had that sorted out everything worked as expected, and I can now create my custom cells all in code without a NIB file.

Posted in mvvmcross, xamarin Tagged with:

MvvmCross – FlyoutNavigation, Hamburger Menu, Sliding Menu for Android and iOS


Provide a unified architecture for a FlyoutNavigation/Hamburger Menu/Sliding Menu across Android and iOS using MvvmCross.


Source Code


FlyoutNavigation, Hamburger Menus, and Sliding Menus (from here on out I’ll refer to this type of control as a slide out menu) all describe a popular method on mobile devices of navigating application windows via a menu that slides/flies out onto the screen providing a user multiple choices on which screen they want to navigate to next.

In my own app Goal Weight I used the popular Xamarin component FlyoutNavigation to show/hide access to settings, set goals, and view weight history.


For my latest project I’ve started development of a time tracking application that will run on Android and iOS. Thus, I found myself needing a cross platform slide out menu.

Existing Work

After Googling and researching StackOverflow I had a couple of contenders for an out of the box solution:

The only rub was neither one of these methodologies shared a common MvvmCross .Core project, and I didn’t want to support multiple/different .Core projects for different platforms. I also had experience with the FlyoutNavigation component and wanted to use it for the iOS solution. Thus I set out to create a unified architecture.

Source Code Walkthrough

The source code up on GitHub is used to demo this unified architecture…think of it as a road map on how to implement a cross platform MvvmCross slide out menu.

The demo application has four ViewModels:

  • HomeViewModel – Holds all of the ViewModels that will appear in the slide out menu
  • EnterTimeViewModel – ViewModel accessible from the slide out menu. In the demo this view is blank.
  • CreateNewJobViewModel – A second ViewModel accessible from the slide out menu. Also blank for this demo.
  • AddNewHoursEntryViewModel – A ViewModel that is created from the EnterTimeViewModel when the user presses a button on the upper right hand corner of the navigation bar.

Android Architecture

Background –
Source –

Android has a slide out menu built into later versions of Android called a Navigation Drawer. James Montemagno does an amazing job implementing the Navigation Drawer on Android in his blog post, so I decided to use his code as a starting point/inspiration for my .Core and .Android projects.

For a full detailed breakdown of the Android architecture read James’ blog. The short version is the HomeViewModel holds the slide out menu items and EnterTimeView and CreateNewJobView are fragments that are swapped in and out of the View as commanded by the slide out menu.

I tore through James’ GitHub code and re-implemented it in my example application to ensure I understood it well enough to keep moving forward. I liked the idea of having one ViewModel to hold all of the menu data and carried this idea over to the iOS application.

iOS Architecture

Warning – Although the iOS architecture works, it doesn’t “feel correct”, i.e. it has a little code smell than I would not normally feel comfortable living with. However I’m happy enough with the solution for now.

With the iOS architecture the idea is simple, construct a FlyoutNavigationController and build up the Views that will populate it in the HomeView.

First build the FlyoutNavigationController and add it to the View.

public override void ViewDidLoad()
    NavigationController.NavigationBarHidden = true;
    Title = "Home";
    this.View = new UIView { BackgroundColor = UIColor.White };

    navigation = new FlyoutNavigationController();


One key point here is NavigationController.NavigationBarHidden = true;, for Views that will be managed from the FlyoutNavigationController we want to use the FlyoutNavigationController‘s navigation bar and not the one supplied by MvvmCross.

Next, we’ll build up the ViewModels and menu elements for the FlyoutNavigationController. Data for the ViewModels and their names are held in the HomeViewModel

//names of the views shown in the flyout
var flyoutMenuElements = new Section();
//views that will be shown when a menu item is selected
var flyoutViewControllers = new List<UIViewController>();
var homeViewModel = ViewModel as HomeViewModel;
if (homeViewModel != null)
    //create the ViewModels
    foreach (var viewModel in homeViewModel.MenuItems)
        var viewModelRequest = new MvxViewModelRequest
            ViewModelType = viewModel.ViewModelType

        flyoutMenuElements.Add(new StringElement(viewModel.Title));
    navigation.ViewControllers = flyoutViewControllers.ToArray();

    //add the menu elements
    var rootElement = new RootElement("")
    navigation.NavigationRoot = rootElement;

Creating the UIViewControllers in CreateMenuItemController

private UIViewController CreateMenuItemController(MvxViewModelRequest viewModelRequest)
    var controller = new UINavigationController();
    var screen = this.CreateViewControllerFor(viewModelRequest) as UIViewController;
    controller.PushViewController(screen, false);
    return controller;

Lastly, we need to listen to two messages that will be emitted by all Views that the FlyoutNavigationController will show. One message to toggle the FlyoutNavigationController‘s menu, and another to show and hide the MvvmCross navigation bar.

var messenger = Mvx.Resolve<IMvxMessenger>();
navigationMenuToggleToken = messenger.SubscribeOnMainThread<ToggleFlyoutMenuMessage>(message => navigation.ToggleMenu());
navigationBarHiddenToken = messenger.SubscribeOnMainThread<NavigationBarHiddenMessage>(message => NavigationController.NavigationBarHidden = message.NavigationBarHidden);

One last item needs to be addressed in our HomeView, setting the size of the Views that will be shown in the FlyoutNavigationController.

public override void ViewWillAppear(bool animated)
    navigation.View.Frame = UIScreen.MainScreen.Bounds;
    navigation.View.Bounds = UIScreen.MainScreen.Bounds;

If we fail to set the FlyoutNavigationController View.Frame and View.Bounds the FlyoutNavigationController will draw all of our views at 2x the Frame size than they should be.

Our HomeView is now complete, let’s take a look at EnterTimeView.


The EnterTimeView is going to show the slide out menu button that when toggled will show the slide out menu, plus it will show another view, the AddHoursEntryView with a button on the upper right of the navigation bar. We’ll add two buttons to the navigation bar with delegates to send message back to the HomeView to perform these actions.

public override void ViewDidLoad()
    View = new UIView { BackgroundColor = UIColor.Blue };

    Title = "Enter Time";
    NavigationItem.LeftBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Pause,
                                       //message to show the menu
                                       var messenger = Mvx.Resolve<IMvxMessenger>();
                                       messenger.Publish(new ToggleFlyoutMenuMessage(this));
    NavigationItem.RightBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Add,
                                       //hide MvvmCross navigation bar and show next view
                                       var messenger = Mvx.Resolve<IMvxMessenger>();
                                       messenger.Publish(new NavigationBarHiddenMessage(this, false));
                                       var viewmodel = ViewModel as EnterTimeViewModel;
                                       if (viewmodel != null) viewmodel.ShowFirstView();


Since we are showing the navigation bar for MvvmCross when we show AddHoursEntryView we need to send a message back to the HomeView to hide it again once AddHoursEntryView is dismissed by the user via the back button.

public override void ViewWillDisappear(bool animated)
    if (!NavigationController.ViewControllers.Contains(this))
        // Back button was pressed.  We know this is true because self is no longer
        // in the navigation stack, hide MvvmCross's navigation menu
        var messenger = Mvx.Resolve<IMvxMessenger>();
        messenger.Publish(new NavigationBarHiddenMessage(this, true)); 

With this last step we have a working slide out menu in iOS that shares a common .Core solution with the Android project.


I have the warning about the iOS code smell because of the extra steps we need to take in the Views to toggle the menu and show/hide the MvvmCross navigation bar. I can’t place my finger on the exact code smell, the solution works…but to me just doesn’t feel “correct” in an Ivory Tower sort of way.

That being said, I believe the extra messaging is a small price to pay to use the FlyoutNavigation component without modification, and to have iOS and Android share a common .Core project.

Go grab the code and try it out,

Posted in mvvmcross, xamarin Tagged with: , , ,

Goal Weight

Just a quick post to announce I’m on the app store!


Posted in Uncategorized

Are You an Athlete?

Lord Stanley’s Cup

I grew up playing hockey.  My parents had me on the ice when I was two, and I have been playing ever since.  Growing up, winters were spent traveling every weekend throughout upstate New York, and weeknights were spent at practices in rinks that only had three solid walls, the forth being a tarp.

Summers were spent traveling from hockey camp to hockey camp, picking up new techniques, and learning edge control from a figure skating coach who emigrated from the USSR.  Once we were home in the summer my brother and I would break out the street hockey nets and start pickup games in front of our house.

It is safe to say hockey dominated my childhood.

The Transition

After high school I stopped playing competitively.  Now, twice a week I break out the equipment.  Pickup hockey is on Sunday night, and Tuesday is league night.  My league team won the championship last fall, yes I am a member of a championship team, a championship beer league team.

Transitioning from competitive hockey to a beer league can be jarring at first.  For one, no more contact.  The game completely changes when you know you are not going to be hit.  Secondly, the amount of ice I see in any given season is drastically less; there are no practices in a beer league.

There are a couple of upsides to playing in a beer league.  Since I know I’m not going to be hit anymore I participate in a lot more risky plays than I did in the past.  Fancy passes, dekes between the legs, having a little “fun” on the ice talking to the players on the other team, most of these things would have been a “no no” in competitive hockey.  Now, however, since nothing is really on the line every game is a fun game where I can go out and really enjoy playing for the sake of playing.

Plus, let’s not forget about the beer in the locker room after the game.  One really couldn’t call it a beer league if there wasn’t beer in the locker room after the game.

I’m not longer striving to be an athlete in hockey, but I am still out there enjoying the game I grew up playing.

The Athlete’s Mentality

Athlete’s practice day in day out, hit the gym, run on their off days, and are constantly preparing for their next game.  Beer league players pick up the equipment once or twice a week, enjoy a relaxing game, and get up the next morning and head into work.  For most of us we can no longer be athletes on the field, but we can each take our athletic mentality and apply it now where it counts the most, in the office.

Do you train and compete like an athlete in the office, or are you merely showing up, collecting a paycheck, and putting in a beer league performance?

To see if you are a beer leaguer or still working on making it to the pros ask yourself a few questions:

Do you read about your industry?

I feel reading is key to staying a head in software development, a topic I have touched on before in My Digital Reading List,

  • Athletes read about their industry in their spare time.
  • Beer leaguers enjoy not knowing about what is happening outside of their cubical.

Do you try new techniques, software packages, and play with new hardware?

Our industry moves fast, staying on top of what others are doing, researching, and implementing is key to staying ahead of the curve.

  • Athletes are always playing with the latest and greatest, they know when to stay with what works, or jump to newer technologies.
  • Beer leaguers wait to be told what hardware and software they should use.

Do you try to learn about tools and techniques outside of your core field of competence?

There are a lot of other industries out there besides software development,

::I know I was shocked too when I heard this news, but there really is!::

…what can we learn from those industries and bring back to our own?  The restaurant industry has been working with and managing teams of people for decades, do they have tools or techniques we could then apply to software development?

  • Athletes learn about other industries outside of their own to learn from them, and see how they would fit in with their primary fields.
  • Beer leaguers have already found their set of tools and don’t want to know what others are doing.

One might not be able to “go pro” in their job, but who are you likely to want to hire, work with, start a startup with, given the chance?

Posted in career, self-management Tagged with: , ,

Breaking Down the Game Film – Voting with Your Dollars

“Breaking Down the Game Film” is a term commonly used to analyze tape from an already played sports game to dissect what went right and what went wrong.  In this series I’ll be taking published articles from around the web and break them down.

Topic: Voting with Your Dollars

Article: “Will Anyone Pay for Anything”

Author: Guy Kawasaki

Links: and video

Guy’s article sums up the video nicely, but I highly suggest watching the video just so you can hear what the panelist say with your own ears.

In the event you are short on time, I’ll save you the click through to the article and the video and sum them both up here:

Guess what teenagers and twenty-somethings are willing to pay for online?


There were only two services any of the panelists were willing to pay for:

  • Gmail
  • Xbox Live

Facebook, Twitter, YouTube…they won’t pay for any of them.  This panel never clicks on banner ads, and if any of the services started charging them money to use them they would move on to find a new service to meet their needs.

Millions of users, and Facebook might loose them all if they ever wanted to charge money.

That is scary.

It turns out developers of all ages are not too different, well, it appears we don’t click on ads at least, as Jeff Atwood laments,,

If Stack Overflow, a site that does a million pageviews a day, can’t make enough from AdSense to pay even one person half time — and let me tell you, that’s being overly generous based on the actual income it generated — how does anyone make a decent living with AdSense?

Thus, teenagers, twenty-somethings, and developers don’t click on ads on the Internet.

I then asked myself two questions:

  1. How does anyone stay in business online?
  2. What would I pay for online if it wasn’t free?

Question one has a myriad of answers that I won’t dive into in this post.  With question two I spent a few minutes and came up with this list:

  • Gmail – Nope, I would put up my own email server if push came to shove.  I already have one on standby just in case.  Better safe than sorry, :-).
  • Xbox Live – This I do pay for, mainly because there is no alternative to play the Xbox online.
  • Facebook – Gone.
  • Twitter – Gone.
  • Flickr – I have already moved to Facebook.  See above for how I feel about paying for Facebook.
  • Stackoverflow – Tougher decision, however there are too many free alternatives out there to fill the void.  Right now when I Google a programming question I’m still finding plenty of links to non-Stackoverflow sites with very good answers.  Someday, but right now, it is a no.
  • Google Reader – Plenty of alternative RSS readers.
  • All of the feeds in my Google Reader – There isn’t a feed/website in my reader that I couldn’t live without.
  • Google – Would I pay for Google?  Again, there are too many free alternatives.

It would be painful to move, change, or lose any of these services/websites, but not painful enough to pay any amount to continue to use them.

Scary thought.


What happens in a world where no one pays for anything and you are the one person who will pay for something?

You might just get everything you ever wanted.

Look at the cartoon Family Guy, from our friends at Wikipedia:

Shortly after the third season of Family Guy aired in 2001, Fox canceled the series.  However, favorable DVD sales and high ratings for syndicated reruns convinced the network to renew the show in 2004.

Family Guy was dead in the water, with no hope to ever see the light of day again.  Then, something crazy happened.  People voted with their dollars, bought the DVDs like crazy, and watched all of the reruns over and over and over again.  Fox woke up, picked the series back up, and Family Guy is entering it’s 8th season.

I’ve decided to start “voting with my dollars” online by monetarily contributing to the following projects that create the plug-ins I use on my blog:

I also purchased an iPhone game I normally wouldn’t have, but I bought it based on the author’s excellent blog posts.  Check out Monkeys in Space from Streaming Colour: and check out Owen Goss great iPhone development blog at

It is my hope to continue to support developers and their projects by contributing to them on a regular basis to further their development.

Next time you find a project, blog, or application you really enjoy I urge you to support it.  By voting with your dollars we have a lot more power online than we realize to influence what survives and what withers.

It is time we all start voting with our dollars!

Posted in Breaking Down the Game Film Tagged with: , ,

Whose Brand are You Building?

Towards the end of 2009 there were two great articles published by two of my favorite bloggers, Joel Spolsky from Fog Creek Software and David Heinemeier from 37signals.

Joel’s post wonders if growing your company too slowly means your company is bound to die:

David responds to Joel in his own post on his blog:

Normally, I would save each one of these links and break them down in my series “Breaking Down the Game Film,” however, there was something else here in these two posts that I thought was more interesting than their primary messages.

Scroll to the bottom of each of the posts and look at the number of comments attached to each one.  I would venture to say there is more written in the comments than in the original posts.  I’ve seen this before, but there was something that really struck me oddly as I compared and contrasted these two articles.

The idea of commenting on an article on the Internet seems to be one of the founding principals of the Internet.  Take, for example, Slashdot is built around people commenting on articles posted all around the Internet.  I have never found this phenomenon of people wanting to comment on other people’s work too interesting before.  In fact I would spend a considerable amount of time reading each one of the comments, never posting mind you, but normally reading the majority of the opinions listed below the articles.

Then something happened, I completely stopped reading comments on other websites.

When I first stopped reading the comments I attributed it to a lack of time-who has the time to scroll through 120 comments for just one article?  After that personal revelation I haven’t given it too much thought, however, lately, after a year of maintaining a technical blog, I realized what my real issue is with comments, and it boils down to this, whose brand are you building?

::We have a blog title, J::

David Heinemeier could have just as easily added his comments below Joel’s article, but he didn’t, he brought the conversation to his own blog.  On 37signals David controls the content, and most importantly of all, he will be able to find his comments again if he ever wants to.  He has a collection of all of his content and thoughts in one location, building his own brand, and his company’s brand on his servers and under his logo.

His thoughts won’t disappear if the server Joel posted his article on ever crashes or that company goes out of business.  His brand is being built in a location he has ultimate control over, and he can assure it never goes away if he chooses to.

Jeff Atwood has covered this topic on his own blog, referring to people who provide content to websites as “digital sharecroppers”.  Jeff doesn’t call out people who comment on blog posts directly, but rather cites the larger trend of people supplying content to the Facebooks and YouTubes of the world:

Ironically, below his post the comments are full with the people doing just what he suggests they shouldn’t.

I agree with Jeff that one should focus on building their own brand.  I’m not suggesting you don’t comment on what you read on the Internet, but rather, if you feel passionately about something you have read take that thought or idea and turn it into a post on your own website, expand upon the points made by the author, and strive to control your own brand.

Posted in blogging, comments Tagged with: