locked
Automatically run a method when the application is open RRS feed

  • Question

  • User384181 posted

    I have application in Xamarin Forms, I want one of the methods of MainPage.xaml.cs to run automatic when the application is open. I want to automatically calla method when the application is open.

    Wednesday, May 15, 2019 10:47 AM

All replies

  • User41045 posted

    @RakeshDasapathri You can always use the PageAppearing event to handle this. https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/app-lifecycle#page-navigation-events

    .

    .

    .



    Looking for Free* Microsoft Support on Xamarin Issues, visit https://aka.ms/xamarinsupport


    Wednesday, May 15, 2019 11:35 AM
  • User382871 posted

    @RakeshDasapathri
    You can add the method in OnStart() in App.class. OnStart() method will be call when the application starts. ``` public partial class App : Application { public App() { InitializeComponent();

        MainPage = new MainPage();
    }
    protected override void OnStart()
    {
        Console.WriteLine("====OnStart====");
        // Handle when your app starts
    }
    protected override void OnSleep()
    {
        // Handle when your app sleeps
    }
    protected override void OnResume()
    {
        // Handle when your app resumes
    }
    

    } ```

    Wednesday, May 15, 2019 11:53 AM
  • User384181 posted

    @yelinzh said: @RakeshDasapathri
    You can add the method in OnStart() in App.class. OnStart() method will be call when the application starts. ``` public partial class App : Application { public App() { InitializeComponent();

        MainPage = new MainPage();
    }
    protected override void OnStart()
    {
        Console.WriteLine("====OnStart====");
        // Handle when your app starts
    }
    protected override void OnSleep()
    {
        // Handle when your app sleeps
    }
    protected override void OnResume()
    {
        // Handle when your app resumes
    }
    

    } ```

    I want to call a method in mainpage.cs, this is not possible with the on start

    Thursday, May 16, 2019 6:22 AM
  • User382871 posted

    @RakeshDasapathri

    I want to call a method in mainpage.cs, this is not possible with the on start.

    What method to call when opening the page? If it is not related to contorls in the page, you can use a static block. If you want to call the control, just add the method to the initialization method of the page.

    ``` public partial class MainPage : ContentPage { //static block static MainPage() { Console.WriteLine("====static method===="); } //initialization method public MainPage() { InitializeComponent();

        Console.WriteLine("====InitializeComponent====");
    }
    

    } ```

    Thursday, May 16, 2019 7:33 AM