In this section, we will take a look at how to update our code-behind file for our WalksMainPage to create and implement a FadingEntrance animation with the FadeTo extension method in the OnAppearing method, using C# code that will be called whenever our ContentPage is displayed.
Let's start updating the code-behind for our WalksMainPage by performing the following steps:
- Locate and open the WalksMainPage.xaml.cs code-behind file, which is located in the Views folder, ensure that it is displayed in the code editor, and enter the following highlighted code sections:
//
// WalksMainPage.xaml.cs
// Displays Walk Information in a ListView control from an array
//
// Created by Steven F. Daniel on 14/05/2018
// Copyright © 2018 GENIESOFT STUDIOS. All rights reserved.
//
using System;
using TrackMyWalks.Models;
using TrackMyWalks.Services;
using TrackMyWalks.ViewModels;
using Xamarin.Forms;
namespace TrackMyWalks.Views
{
public partial class WalksMainPage : ContentPage
{
// Return the Binding Context for the ViewModel
WalksMainPageViewModel _viewModel =>
BindingContext as WalksMainPageViewModel;
public WalksMainPage()
{
InitializeComponent();
...
...
}
...
...
// Method to initialise our View Model when the ContentPage appears
protected override async void OnAppearing()
{
base.OnAppearing();
if (_viewModel != null)
{
// Call the Init method to initialise the ViewModel
await _viewModel.Init();
}
// Create a FadingEntrance Animation to fade our WalkEntriesListView
WalkEntriesListView.Opacity = 0;
await WalkEntriesListView.FadeTo(1, 4000);
...
...
}
}
}
Let's take a look at what we covered in the preceding code snippet:
- We started by modifying our OnAppearing method to create a FadingEntrance animation, and set the Opacity property for our WalkEntriesListView to fade our ListView.
- We used the FadeTo extension method, which will animate our WalkEntriesListView, and we specified the Opacity value to fade to, as well as specifying a duration in milliseconds of 4 seconds over which to animate the transition.
For more information on the FadeTo extension method, please refer to the Xamarin.Forms documentation at https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.viewextensions.fadeto?view=xamarin-forms