4

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?

Jimmy
  • 1,299
  • 2
  • 10
  • 14

2 Answers2

4

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

iam.Carrot
  • 4,976
  • 2
  • 24
  • 71
  • Wow. Thanks for the detailed post. I will try this and let you know if I have any issues. I appreciate the help. – Jimmy Oct 27 '17 at 20:03
  • 1
    @Jimmy has the issue been resolved by this answer? if yes could you please mark my answer as correct (or even upvote it, if you liked the approach) so that this thread will be closed? – iam.Carrot Nov 21 '17 at 18:02
3

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

    }
}

ʞᴉɯ
  • 5,376
  • 7
  • 52
  • 89