Working with Xamarin Forms App Class


Isn't it fun,

to instantly listen to a blog on the go? PLAY !

 
 

ai-Hiring-banner

The app class is the root page of the application. It’s a default created class when we start a visual studio and create a project, then the app class can be created. App class has lifecycle methods like an OnStart, OnResume, and OnSleep and also contains the model navigation events.

Table of Content

Let’s see the Lifecycle method of an Application.

  1. OnStart: This method is called when the application is started.
  2. OnSleep: This method is called that all-time when the application goes to the background. In this method application goes to sleep not stop.
  3. OnResume: This method works similar to its name and when the method is called the application is resumed.

Using the WriteLine we can check when the method is called for each platform.

using System.Diagnostics;
using Xamarin.Forms;

namespace AppClassExample
{
    public partial class App: Application
    {
        public App ()
        {
            InitializeComponent();

            MainPage = new MainPage();
        }

        protected override void OnStart()
        {
            Debug.WriteLine("OnStart");
        }

        protected override void OnSleep()
        {
            Debug.WriteLine("OnSleep");
        }

        protected override void OnResume()
        {
            Debug.WriteLine("OnResume");
        }
    }
}

There are two ways to define App class in your project.

1.C#, or

2.XAML & C#

Let’s see both ways how we can implement app class in XAML or C#.

In XAML,



    

    

In code-behind,

public partial class App: Application
    {
        public App ()
        {
            InitializeComponent();

            MainPage = new MainPage();
        }
    }

InitializeComponent method can load the associated XAML. We can see the MainPage in code-behind the MainPage property on the App class that is used to set the root page of the application. MainPage is by default set as the initial page for the page. We can set or display the property of MainPage in the App constructor.

using System.Diagnostics;
using Xamarin.Forms;

namespace AppClassExample
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();

            MainPage = new ContentPage {Title = "Sample of display properties in App class.”};
        }
    }
}

In iOS,

In the iOS project, the AppDelegate class is used for loading an application and the AppDelegate class inherits from the FormsApplicationDelegate.

To load the iOS application, we can call the LoadApplication with the instance of App class, and the lastly we need to return base.FinishedLaunching(app, options); .

using System;
using System.Collections.Generic;
using System.Linq;

using Foundation;
using UIKit;

namespace AppClassExample.iOS
{
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        override bool FinishedLaunching(UIApplication application, NSDictionary opt)
        {
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());

            return base.FinishedLaunching(application, opt);
        }
    }
}

In Android,

In the android project, MainActivity class is used for loading an application. This class inherits from FormsAppCompatActivity. In MainActivity class, the OnCreate method overrides the LoadApplication.

using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace AppClassExample.Droid
{
    [Activity(Label = "TestExample", Icon = "@mipmap", Theme = "@style", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
        override void Result (int rc, string[] permit, [GeneratedEnum] Android.Content.PM.Permission[] Results)
        {
            Xamarin.Essentials.Platform.PermissionsResult(rc, permit,Results);

            base.PermissionsResult(rc, permit, Results);
        }
    }
}

Properties:

BindingContext: This property is used to get and set the properties that will be targeted by the bound properties.

ClassId: This property is used to get and set the value to identify a similar element in the collection.

Current: This property is used to get the current application.

Effects: The use of this property is to applied effects on a list of items.

MainPage: This property is used to get and set the root page of the application.

AppLinks: Use of this property is to register or unregister the application links. Using the object user can register or unregister the application links.

Parent: Use of this property is to get or set the parent element of the element.

StyleId: This property is used to uniquely identify the element.

Methods: -

ApplyBindings(): BindingContext is used to apply the bindings and this method is inherited from the BindableObject.

ClearValue(): Use of this method is to clear any value of a property by using SetValue.

FindByName(): Using this method we can return the element that has the specified name.

GetValue(): Use of this method is to return a value contained in BindableProperty.

IsSet(): This method is used when the target property has been set and the target property exists it returns true.

OnBindingContextChanged(): This method is called when the element of the binding context is changed.

OnPropertyChanged(): This method is called when the bindable property is changed.

OnStart(): This method is called on application start time so the developer can override this method to perform any other action on starting an application.

OnSleep(): This method is used when we want to perform some action when the application goes to sleeping mode. A developer can override this method and perform any other actions.

OnResume(): This method is called when the application resumes from a sleeping state. A developer can override this method when the application goes to resume from sleeping state.

Quit (): When we want to quit the application, this method is used to quit the application.

RemoveBinding(): Use of this method is to remove the previously set binding.

RemoveDynamicResource(): Use of this method is to remove the previously set dynamic resource.

SetBinding(): Using this method we can assign a binding to a property.

SetValue(): This method is used when we want to set the value of the specified property.

UnapplyBindings(): Use of this method is to unapplied all the previously set bindings.

Events

BindingContextChanged: This event occurs when the BindingContext property can changes.

ChildAdded: This event occurs when the child element of the element is added.

ChildRemove: This event occurs when the child element of the element is removed.

PropertyChanged: This event occurs when the property has changed.

PropertyChanging: This event occurs when the property is about to change.

ModelPopped: This event occurs after a view has been popped modally.

ModelPushed: This event occurs after a view has been pushed modally.

Conclusion

In this blog, we could see how the App class file is important to the application. Using this app file, we can add a common style for all a common control using a single code. We can also make another page to the default page and navigate a page based on conditions in the App class.

ai-Hiring-banner

The app class is the root page of the application. It’s a default created class when we start a visual studio and create a project, then the app class can be created. App class has lifecycle methods like an OnStart, OnResume, and OnSleep and also contains the model navigation events.

Table of Content

Let’s see the Lifecycle method of an Application.

  1. OnStart: This method is called when the application is started.
  2. OnSleep: This method is called that all-time when the application goes to the background. In this method application goes to sleep not stop.
  3. OnResume: This method works similar to its name and when the method is called the application is resumed.

Using the WriteLine we can check when the method is called for each platform.

using System.Diagnostics;
using Xamarin.Forms;

namespace AppClassExample
{
    public partial class App: Application
    {
        public App ()
        {
            InitializeComponent();

            MainPage = new MainPage();
        }

        protected override void OnStart()
        {
            Debug.WriteLine("OnStart");
        }

        protected override void OnSleep()
        {
            Debug.WriteLine("OnSleep");
        }

        protected override void OnResume()
        {
            Debug.WriteLine("OnResume");
        }
    }
}

There are two ways to define App class in your project.

1.C#, or

2.XAML & C#

Let’s see both ways how we can implement app class in XAML or C#.

In XAML,



    

    

In code-behind,

public partial class App: Application
    {
        public App ()
        {
            InitializeComponent();

            MainPage = new MainPage();
        }
    }

InitializeComponent method can load the associated XAML. We can see the MainPage in code-behind the MainPage property on the App class that is used to set the root page of the application. MainPage is by default set as the initial page for the page. We can set or display the property of MainPage in the App constructor.

using System.Diagnostics;
using Xamarin.Forms;

namespace AppClassExample
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();

            MainPage = new ContentPage {Title = "Sample of display properties in App class.”};
        }
    }
}

In iOS,

In the iOS project, the AppDelegate class is used for loading an application and the AppDelegate class inherits from the FormsApplicationDelegate.

To load the iOS application, we can call the LoadApplication with the instance of App class, and the lastly we need to return base.FinishedLaunching(app, options); .

using System;
using System.Collections.Generic;
using System.Linq;

using Foundation;
using UIKit;

namespace AppClassExample.iOS
{
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        override bool FinishedLaunching(UIApplication application, NSDictionary opt)
        {
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());

            return base.FinishedLaunching(application, opt);
        }
    }
}

In Android,

In the android project, MainActivity class is used for loading an application. This class inherits from FormsAppCompatActivity. In MainActivity class, the OnCreate method overrides the LoadApplication.

using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace AppClassExample.Droid
{
    [Activity(Label = "TestExample", Icon = "@mipmap", Theme = "@style", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
        override void Result (int rc, string[] permit, [GeneratedEnum] Android.Content.PM.Permission[] Results)
        {
            Xamarin.Essentials.Platform.PermissionsResult(rc, permit,Results);

            base.PermissionsResult(rc, permit, Results);
        }
    }
}

Properties:

BindingContext: This property is used to get and set the properties that will be targeted by the bound properties.

ClassId: This property is used to get and set the value to identify a similar element in the collection.

Current: This property is used to get the current application.

Effects: The use of this property is to applied effects on a list of items.

MainPage: This property is used to get and set the root page of the application.

AppLinks: Use of this property is to register or unregister the application links. Using the object user can register or unregister the application links.

Parent: Use of this property is to get or set the parent element of the element.

StyleId: This property is used to uniquely identify the element.

Methods: -

ApplyBindings(): BindingContext is used to apply the bindings and this method is inherited from the BindableObject.

ClearValue(): Use of this method is to clear any value of a property by using SetValue.

FindByName(): Using this method we can return the element that has the specified name.

GetValue(): Use of this method is to return a value contained in BindableProperty.

IsSet(): This method is used when the target property has been set and the target property exists it returns true.

OnBindingContextChanged(): This method is called when the element of the binding context is changed.

OnPropertyChanged(): This method is called when the bindable property is changed.

OnStart(): This method is called on application start time so the developer can override this method to perform any other action on starting an application.

OnSleep(): This method is used when we want to perform some action when the application goes to sleeping mode. A developer can override this method and perform any other actions.

OnResume(): This method is called when the application resumes from a sleeping state. A developer can override this method when the application goes to resume from sleeping state.

Quit (): When we want to quit the application, this method is used to quit the application.

RemoveBinding(): Use of this method is to remove the previously set binding.

RemoveDynamicResource(): Use of this method is to remove the previously set dynamic resource.

SetBinding(): Using this method we can assign a binding to a property.

SetValue(): This method is used when we want to set the value of the specified property.

UnapplyBindings(): Use of this method is to unapplied all the previously set bindings.

Events

BindingContextChanged: This event occurs when the BindingContext property can changes.

ChildAdded: This event occurs when the child element of the element is added.

ChildRemove: This event occurs when the child element of the element is removed.

PropertyChanged: This event occurs when the property has changed.

PropertyChanging: This event occurs when the property is about to change.

ModelPopped: This event occurs after a view has been popped modally.

ModelPushed: This event occurs after a view has been pushed modally.

Conclusion

In this blog, we could see how the App class file is important to the application. Using this app file, we can add a common style for all a common control using a single code. We can also make another page to the default page and navigate a page based on conditions in the App class.