Conditional Back Button Visibility with BuildIt.Lifecycle

In my post, Adding Back Button Support to Xamarin.Forms with BuildIt.Forms, I showed the basic support I’d added to BuildIt.Lifecycle to handle showing/hiding the back button depending on whether there were previous states. The back button visibility is actually more complex than that as there may be conditions on the current page (ie the current state/view model) that determine whether clicking back should be possible. To keep things simple I’m going to assume that if clicking back is possible, the back button will be shown, otherwise it will be hidden – this may not suit everyone as you may want to show the back button but have it disabled (personally I don’t like this, as it’s hard for the user to understand why the back button is disabled). I’ve just added support to the states and corresponding viewmodel management to detect if the current view model is in a blocked state.

There is an interface IIsAbleToBeBlocked that a view model can implement in order to both return an IsBlocked property and raise an event when it changes. This interface has also been added to the BaseViewModel class to make it easier for developers. For example this method can be used within a view model to toggle the visibility of the back button. If IsBlocked is true, the back button will be hidden.

public async void Run()
{
    for (int i = 0; i < 10; i++)
    {
        IsBlocked = !IsBlocked;
        await Task.Delay(1000);
    }
}

Note that the IsBlocked property works in conjunction with the HasHistory property on the state group (which maps to the back stack at a page level). If there is no history in the state group (ie at the first stage of the application – the first page of the application), then the back button won’t be shown, irrespective of the IsBlocked property.

Leave a comment