System.InvalidOperationException:'如果没有元素,则无法分配本机控件; Xamarin格式中的异常

问题描述 投票:0回答:1

我想将Microsoft Ads集成到我的Xamarin.Forms项目中。我已经实施了Microsoft广告,如图in this tutorial by James Montemagno所示。我在2页上添加了横幅广告。横幅广告显示在第一页和第二页上。首先在应用启动时将广告显示在第一页,然后在第二页显示广告。但是,一旦我从第二页回到第一页,我会收到此错误

System.InvalidOperationException: 'Cannot assign a native control without an Element; Renderer unbound and/or disposed. Please consult Xamarin.Forms renderers for reference implementation of OnElementChanged.'

我也曾提到this answer on Stackoverflow。当我将代码实现为此处给出的答案时,从第二页返回时,第一页上没有任何广告。

这是我的代码:

[assembly: ExportRenderer(typeof(MicrosoftBannerAdControlView), typeof(MicrosoftBannerAdsImplementation))]
namespace AdExampleApp.UWP.PlatformSpecific.MicrosoftAdsImplementation
{
    public class MicrosoftBannerAdsImplementation : ViewRenderer<Controls.AdsControl.MicrosoftAds.MicrosoftBannerAdControlView, AdControl>
    {
        string bannerId = "test";
        AdControl adView;
        string applicationId = "3f83fe91-d6be-434d-a0ae-7351c5a997f1";
        bool isRegist = false;

        protected override void OnElementChanged(ElementChangedEventArgs<MicrosoftBannerAdControlView> e)
        {
            base.OnElementChanged(e);

            if (Control == null && isRegist != true)
            {
                CreateNativeAdControl();
                SetNativeControl(adView);     // I am getting the ERROR Here
                isRegist = true;
            }
        }

        void CreateNativeAdControl()
        {
            if (adView != null)
                return;
            var width = 300;
            var height = 50;
            if (AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Desktop")
            {
                width = 728;
                height = 90;
            }
            adView = new AdControl
            {
                ApplicationId = applicationId,
                AdUnitId = bannerId,
                HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center,
                VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Bottom,
                Height = height,
                Width = width
            };
        }
    }
}

这是我的第一页的XAML代码

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             ....
             xmlns:MicrosoftAds="clr-namespace:AdExampleApp.Controls.AdsControl.MicrosoftAds">

    <ContentPage.Content>
        <StackLayout>
            <Button Text="Go To Page 2" Clicked="GoToPage2" />
            <MicrosoftAds:MicrosoftBannerAdControlView x:Name="MicrosoftBannerAd" VerticalOptions="EndAndExpand" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

我在第二页上也类似地实施了Microsoft Ads。它在第一页和第二页上显示广告,但是当我从第二页返回首页时,出现错误。

c# xamarin xamarin.forms uwp xamarin.uwp
1个回答
0
投票

恐怕我们不能再在UWP平台中使用AdControl。派生official解释:

自2020年6月1日起,用于Windows UWP应用程序的Microsoft Ad Monetization平台将关闭。之所以做出此决定,主要是因为我们不再能够以当前水平继续使用该产品。

抱歉给您带来的不便。

© www.soinside.com 2019 - 2024. All rights reserved.