Xamarin.Forms - ContentView Lifecycle

Introduction

Xamarin.Forms code runs on multiple platforms, each of which has its own filesystem. This means that reading and writing files are 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 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. 

ContentView Lifecycle

Create Interface

Here, we need to create an interface for the renderer resolver

IRendererResolver.cs

public interface IRendererResolver
{
    object GetRenderer(VisualElement element);

    bool HasRenderer(VisualElement element);
}

Platform Implementation 

Android Implementation

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

AndroidRendererResolver.cs

[assembly: Dependency(typeof(AndroidRendererResolver))]
namespace XamarinStudy.Droid.Renderer
{
    public class AndroidRendererResolver: IRendererResolver
    {
        public object GetRenderer(VisualElement element)
        {
            return Xamarin.Forms.Platform.Android.Platform.GetRenderer(element);
        }

        public bool HasRenderer(VisualElement element)
        {
            return GetRenderer(element) != null;
        }
    }
}

iOS Implementation

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

IosRendererResolver.cs

[assembly: Dependency(typeof(IosRendererResolver))]
namespace XamarinStudy.iOS.Renderer
{
    public class IosRendererResolver: IRendererResolver
    {
        public object GetRenderer(VisualElement element)
        {
            return Xamarin.Forms.Platform.iOS.Platform.GetRenderer(element);
        }

        public bool HasRenderer(VisualElement element)
        {
            return GetRenderer(element) != null;
        }
    }
}

Setup UI

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

CommonListview.xaml

<?xml version="1.0" encoding="UTF-8" ?>
<ContentView
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:sfl="clr-namespace:Syncfusion.ListView.XForms;assembly=Syncfusion.SfListView.XForms"
    xmlns:sfp="clr-namespace:Syncfusion.SfPullToRefresh.XForms;assembly=Syncfusion.SfPullToRefresh.XForms"
    x:Class="XamarinStudy.CustomView.CommonListview">
    <ContentView.Content>
        <ListView ItemsSource="{Binding ProductList}" ItemSelected="ListView_ItemSelected">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                        <StackLayout HeightRequest="100">
                           <Label Text="{Binding .}"/>
                        </StackLayout>
                            </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
    </ContentView.Content>
</ContentView>

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

public partial class CommonListview : ContentView
{
    public CommonListview()
    {
        InitializeComponent();
    }

    
    private ContentPage _parentPage;
    private bool _registered;

   
    protected virtual void OnAppearing()
    {
    }

    protected virtual void OnDisappearing()
    {
    }

    protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        base.OnPropertyChanged(propertyName);

        if (propertyName.Equals("Renderer", StringComparison.OrdinalIgnoreCase))
        {
            var rr = DependencyService.Get<IRendererResolver>();

            if (rr.HasRenderer(this))
            {
                Unregister();

                var parent = Parent;
                while (parent?.Parent != null && !(parent is ContentPage))
                {
                    parent = parent.Parent;
                }

                if (parent is ContentPage page)
                {
                    _parentPage = page;
                    Register();
                }
            }
            else
            {
                Unregister();
            }
        }
    }

    private void Register()
    {
        if (_parentPage != null && !_registered)
        {
            _parentPage.Appearing += OnAppearing;
            _parentPage.Disappearing += OnDisappearing;

            _registered = true;
        }
    }

    private void Unregister()
    {
        if (_parentPage != null && _registered)
        {
            _parentPage.Appearing -= OnAppearing;
            _parentPage.Disappearing -= OnDisappearing;

            _registered = false;
            _parentPage = null;
        }
    }

    private void OnAppearing(object sender, EventArgs e)
    {
        OnAppearing();
    }

    private void OnDisappearing(object sender, EventArgs e)
    {
        OnDisappearing();
    }
}

OnAppearing

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

ContentView Lifecycle

OnDisAppearing

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

ContentView Lifecycle

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 :)


Similar Articles