Delpin Susai Raj Thursday, 30 September 2021

Xamarin.Forms - ContentView Lifecycle

In this blog post, you will learn how to use OnAppearing and OnDisAppearing in ContentView in Xamarin forms.

Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

ContentView LifeCycle

  • OnAppearing - raised when a View is about to appear on the screen.
  • OnDisAppearing - raised when a View is about to disappear from the screen.

Problem

In Xamarin.froms Content view or any custom view we develop. Here there are no lifecycle methods like OnStart, OnAppearing. this one is a major requirement for Xamarin.forms.

Solution

There is one workaround for OnAppearing and OnDisappearing in ContentView we can invoke the parent page OnAppearing and OnDisAppearing to our ContentView. Please follow all steps.

Prerequisites

  • Visual Studio 2017 or later (Windows or Mac)

Let's Start,

Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You will learn more by going through the steps yourself.

Create a new or existing Xamarin forms(.Net standard) Project. With Android and iOS Platform.

Create Interface

Here, need to create an interface for the renderer resolver

IRendererResolver.cs

Platform Implementation

Android Implementation

Create AndroidRendererResolver in your android project. And add the following code snippets.

AndroidRendererResolver.cs

iOS Implementation

Create an iOSRenderderResolver for iOS in your iOS project. And copy-paste the following code.

IosRendererResolver.cs

Setup UI

Now, create a UI for your requirement in your ContentView.

CommonListview.xaml

ContentView LifeCycle

Following code for OnAppearing and OnDisAppearing in your ContentView. Now you can do whatever you want in your ContentView OnAppearing and OnDisAppearing.

CommonListView.xaml.cs

OnAppearing

See below screenshot of the breakpoint triggered in OnAppearing when the view is loaded.

OnDisAppearing

See below screenshot of the breakpoint triggered in OnDisAppearing when the view is unloaded.

Conclusion

I hope you have understood how to use add OnAppearing and OnDisAppearing in ContentView in Xamarin.Forms App.

Thanks for reading. Please share your comments and feedback. Happy Coding :)