【问题标题】:UWP AdControl blank after PopAsync in Xamarin FormsXamarin Forms 中的 PopAsync 后 UWP AdControl 空白
【发布时间】:2018-10-06 20:01:06
【问题描述】:

使用 Microsoft Advertising AdControl 的 Xamarin Forms 项目。打开页面时控件工作正常,但是当页面在其顶部的页面的 PopAsync 之后再次显示页面时,AdControl 为空白,之后保持空白。

我发现了一个似乎关于同一主题的老问题here,但我无法使用答案和 cmets。

当带有 AdControl 的页面在其顶部的页面的 PopAsync 之后重新出现时,e.NewElement 为 null 并且 e.OldElement 具有 AdControlView(我在 PCL 中的自定义视图)。

UWP 渲染器:

public class AdViewRenderer : ViewRenderer<AdControlView, UWPAdView>
{
    protected override void OnElementChanged(ElementChangedEventArgs<AdControlView> e)
    {
        base.OnElementChanged(e);

        if (null == Control && e.NewElement != null)
        {
            UWPAdView ad = new UWPAdView();
            SetNativeControl(ad);
        }
    }
}

UWP 项目中的 AdControl 用户控件:

<UserControl
    x:Class="Sample.UWP.Helpers.UWPAdView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:aduwp="using:Microsoft.Advertising.WinRT.UI"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    d:DesignHeight="300"
    d:DesignWidth="400"
    mc:Ignorable="d">

    <Grid>
        <aduwp:AdControl
            Width="640"
            Height="100"
            HorizontalAlignment="Stretch"
            AdUnitId="myadunitid"
            ApplicationId="myappid"
            AutoRefreshIntervalInSeconds="30"
            ErrorOccurred="AdControl_ErrorOccurred"
            IsAutoRefreshEnabled="True" />
    </Grid>
</UserControl>

是否有人在 Xamarin Forms UWP 生产应用中使用 AdControl?

【问题讨论】:

    标签: forms xamarin uwp ads


    【解决方案1】:

    通过我这边的测试,当第二个页面调用PopAsync()时,第二个页面实例要从导航堆栈中删除,新的最顶层页面成为活动页面,但当前最顶层页面似乎不会创建一个新实例,但缓存旧实例。这应该符合预期,但是您的AdControl 也没有刷新,并且AdControl 的Refresh 事件不会被触发,它保持空白。

    要解决这个问题,您可以考虑自己强制刷新控件。您可能需要在包含AdControl 的第一页中覆盖OnAppearing 方法,因为要返回的页面已调用此方法覆盖。一旦返回第一页,OnAppearing 将被调用,您可以在此方法中根据需要执行某些操作来强制刷新AdControl。举个例子,在这里我重新初始化可以工作的页面:

    public MainPage()
    {
        InitializeComponent() 
    }
    
    async void OnButtonClicked(object sender, EventArgs args)
    {
        await Navigation.PushAsync(new Page2());  
    }
    protected override void OnAppearing()
    {
        base.OnAppearing();
        InitializeComponent();
    }
    

    更多详情请参考this document。

    【讨论】:

    • 谢谢,这行得通。但是,在页面执行很多高级操作的地方,再次调用InitializeComponent() 会变得非常混乱。在AdControl 上调用Refresh 事件会更顺畅。
    猜你喜欢
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多