首页 > 解决方案 > 将 DeviceDisplay.MainDisplayInfoChanged 事件添加到 XF 应用程序的 OnStart 是否有任何问题?

问题描述

我的应用程序有这个代码:

    protected override void OnStart()
    {
        base.OnStart();
        DeviceDisplay.MainDisplayInfoChanged += OnMainDisplayInfoChanged 
    }

    private void OnMainDisplayInfoChanged(object sender, DisplayInfoChangedEventArgs e)
    {
        SetDeviceInfo();
        SetResourceDimensions();
    }

我已经读过 Android 可以多次调用 OnStart。有人可以告诉我这是否会导致我在其中注册 OnMainDisplayInfoChanged 方法的代码出现问题。

标签: xamarinxamarin.forms

解决方案


在您的情况下,因为该方法OnStart()将被多次调用。该方法OnMainDisplayInfoChanged 可能会同时被多次调用。因为方法列表 MainDisplayInfoChanged 有重复的方法。

所以我们可以MainDisplayInfoChanged在添加之前删除它。

bool IsFirstLoad = true;
protected override void OnStart()
{
   base.OnStart();

   

   if(!IsFirstLoad)
   {
       DeviceDisplay.MainDisplayInfoChanged -= OnMainDisplayInfoChanged 
   }

   DeviceDisplay.MainDisplayInfoChanged += OnMainDisplayInfoChanged;
   IsFirstLoad = false ;
}

推荐阅读