Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get notified when ContentPage finishes loading

Tags:

c#

xaml

xamarin

I've got some XAML ContentPages that have ContentView objects on them. So, typically I size these objects based on this.Width and this.Height, values that are set in the ContentPage. But, if there's not something explicitly calling my ContentView objects AFTER the ContentPage has loaded, the Width and Height values are null because the values aren't yet set.

What I'm trying to figure out is, how can I tell my ContentViews to wait until the ContentPage is done loading before it gets the Width and Height values?

like image 255
Jimmy Avatar asked Mar 08 '23 17:03

Jimmy


2 Answers

Xamarin.Forms provides two lifecycle-type events:

  1. OnAppearing
  2. OnDisappearing

which can be overridden in Page subclasses.

Now the fact, OnAppearing will be executed before the screen comes, when you want an Loaded event that needs to be executed right after the screen comes, there is a workaround.

The work around

  1. Create an property in viewmodel like below.

private bool _toggleTemp;
public bool ToggleTemp
{
    get => _toggleTemp;
    set => SetProperty(ref _toggleTemp, value);
}
  1. Add the following line to the last line of the constructor. LoadingVm.ToggleTemp = true;
  2. Add an Switch to your screen and make IsVisible to false as below. (just for demo purposes)

<Switch IsToggled="{Binding ToggleTemp}" Toggled="Switch_OnToggled" IsVisible="False" />
  1. Now you can write the code that you want to write in Page Loaded in Switch_OnToggled.

private async void Switch_OnToggled(object sender, ToggledEventArgs e)
{ 
    /* Your code goes here... */ 
}

Please let me know if you have any doubts

like image 125
iam.Carrot Avatar answered Mar 17 '23 21:03

iam.Carrot


I've found another workaround and it is working in Xamarin Forms 4.8:

private bool isStarted = false;
protected override void LayoutChildren(double x, double y, double width, double height)
{
    base.LayoutChildren(x, y, width, height);
    if (!isStarted)
    {
        isStarted = true;
        // do something

    }
}

like image 28
ʞᴉɯ Avatar answered Mar 17 '23 21:03

ʞᴉɯ