当 ContentPage 完成加载时如何获得通知 [英] How to get notified when ContentPage finishes loading

查看:23
本文介绍了当 ContentPage 完成加载时如何获得通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些包含 ContentView 对象的 XAML ContentPage.因此,通常我会根据在 ContentPage 中设置的 this.Width 和 this.Height 值来调整这些对象的大小.但是,如果在 ContentPage 加载后没有明确调用我的 ContentView 对象,则 Width 和 Height 值为空,因为这些值尚未设置.

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.

我想弄清楚的是,如何告诉我的 ContentViews 在获得 Width 和 Height 值之前等待 ContentPage 完成加载?

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?

推荐答案

Xamarin.Forms 提供了两个生命周期类型的事件:

Xamarin.Forms provides two lifecycle-type events:

  1. OnAppearing
  2. 消失

可以在 Page 子类中覆盖.

which can be overridden in Page subclasses.

现在事实是,OnAppearing 将在屏幕出现之前执行,当您想要一个需要在屏幕出现后立即执行的 Loaded 事件时,有一个解决方法.

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.

  1. 在视图模型中创建一个属性,如下所示.

<小时>

private bool _toggleTemp;
public bool ToggleTemp
{
    get => _toggleTemp;
    set => SetProperty(ref _toggleTemp, value);
}

  1. 将以下行添加到构造函数的最后一行.LoadingVm.ToggleTemp = true;
  2. 在您的屏幕上添加一个 Switch 并将 IsVisible 设置为 false,如下所示.(仅用于演示目的)

<小时>

<Switch IsToggled="{Binding ToggleTemp}" Toggled="Switch_OnToggled" IsVisible="False" />

  1. 现在您可以在 Switch_OnToggled 中的 Page Loaded 中编写您想要编写的代码.

<小时>

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

如果您有任何疑问,请告诉我

Please let me know if you have any doubts

这篇关于当 ContentPage 完成加载时如何获得通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆