View Model States and Connecting them to Xamarin Forms Visual States using BuildIt

In my previous post on Getting Started with Visual States in Xamarin Forms using BuildIt.Forms I showed a very basic example of defining and triggering Visual States within a Xamarin Forms application. However, most applications have more complexity where each page is typically data bound to a corresponding ViewModel and it is the ViewModel which encapsulated the logic of the application.

Let me walk through working with a ViewModel using the same basic example I started in my previous post. In this case I’m going to add another panel to the page which will be displayed after the user clicks the Login button, effectively simulating the experience of showing a progress indicator whilst the application is authenticating the user.

<!– Authenticating Prompt –>
<Grid BackgroundColor=”LightPink”
         x_Name=”AuthenticatingIndicator”
         IsVisible=”false”>
     <Label Text=”Attempting to authenticate you…”
             HorizontalTextAlignment=”Center”
             VerticalOptions=”Center” />
</Grid>
<!– END Authenticating Prompt –>

In this case I’m going to add a new VisualStateGroup to define the visual states to hide and show the AuthenticatingIndicator Grid.

<vsm:VisualStateGroup Name=”AuthenticationStates”>
     <vsm:VisualState Name=”Authenticating”>
         <vsm:VisualState.Setters>
             <vsm:Setter Element=”{x:Reference AuthenticatingIndicator}”
                         Property=”IsVisible”
                         Value=”true” />
         </vsm:VisualState.Setters>
     </vsm:VisualState>
     <vsm:VisualState Name=”NotAuthenticating” />
</vsm:VisualStateGroup>

A VisualStateGroup is designed to hold mutually exclusive states. A page can have any number of VisualStateGroups, and at any given point in time the current state of the page can consist of being in one VisualState from each group. In this scenario we have broken the authenticating states away from the loading states because in theory you might want to disply both the AuthenticatingIndicator, as well as the LoadingIndicator.

The last piece of XAML that I need to update is to attach an event handler to the Clicked event of the Button:

<Button Text=”Login”
         Clicked=”LoginPressed” />

And in the code behind, define the corresponding LoginPressed method (and yes, those MVVM purist will argue that this would be better using the Command property through to the ViewModel but we’ll leave that for another post):

protected async void LoginPressed(object sender, EventArgs e)
{
}

Now that we have the XAML defined, it’s time to look at how we can drive this from our ViewModel. In my case the page I’m working with is called MainPage.xaml, so I’m going to define a class called MainViewModel in a separate .NET Standard library. I’m not going to add a reference to BuildIt.Forms to the .NET Standard library because that would bring in a reference to Xamarin Forms, which should not be referenced by the library that holds your ViewModels – they should be abstracted away from any concrete interface, which includes Xamarin Forms, even though it is itself an abstraction from the native platform interfaces. What I am going to reference is the BuildIt.States library, which is a .NET Standard library that has no reference to any specific user interface framework, making it perfect for managing states within your ViewModel.

Alongside the MainViewModel class I’m also going to define an enumeration where the names match the corresponding visual states: the enum type name has to match the VisualStateGroup name and the enum values have to match the VisualState name.

public enum AuthenticationStates
{
     Base,
     Authenticating,
     NotAuthenticating
}

The enum also has an additional value, Base, which is will be the default enum value. The name of this value is irrelevant but it’s important to have it as the first value and should not correspond to any VisualState name.

The MainViewModel class includes a StateManager property. In this case the constructor calls the extension method DefineAllStates to define states for each value of the AuthenticationState enum. The BuildIt States library has a host of great features that are worth explaining but I’ll save that topic for another post. The important thing is that each of the states for the AuthenticationState enum are defined.

public class MainViewModel
{
     public IStateManager StateManager { get; } = new StateManager();


    public MainViewModel()
     {
         StateManager.Group<AuthenticationStates>().DefineAllStates();
     }


    public async Task Login()
     {
         await StateManager.GoToState(AuthenticationStates.Authenticating);


        await Task.Delay(2000);


        await StateManager.GoToState(AuthenticationStates.NotAuthenticating);
     }
}

The Login method simply calls the GoToState method prior to calling Task.Delay, to simulate attempting to authenticate the user, and then again calling GoToState to change the state back to the NotAuthenticating state.

Now that we have our MainViewModel defined, I need to connect it to my MainPage. For real applications we work on at Built to Roam, we use frameworks such as MvvmCross to connect the View and ViewModels. However, for brevity I’m going to simply create an instance of the MainViewModel as part of the MainPage:

private MainViewModel ViewModel { get; } = new MainViewModel();

And then set the instance as the BindingContext of the page, in the constructor:

public MainPage()
{
     InitializeComponent();


    BindingContext = ViewModel;
}

Lastly, I’ll update the LoginPressed method to call the method on the MainViewModel:

protected async void LoginPressed(object sender, EventArgs e)
{
     await ViewModel.Login();
}

At this point we’re almost done: We have a ViewModel that defines the states of the application in a way that they can be tested in absence of any user interface implementation, and the View (in this case the MainPage) will invoke the Login method to trigger the state changes. The only missing component is connecting the Visual States defined on the MainPage XAML, with the states defined in the MainViewModel. This is done using the Bind method within the OnAppearing override:

await VisualStateManager.Bind(this, ViewModel.StateManager);

Now I’m ready to go – at this point the user experience is entirely defined in XAML, with all my logic, including the states, encapsulated within my ViewModel, ready to be tested.

Leave a comment