我正在开发一个“CoManga”项目,我想在其中添加广告。在UWP上实施广告似乎很简单,如Android和iOS。但是,我现在被困住了。
无论如何,我跟着this tutorial by James Montemagno并添加了一切。我甚至看到了测试广告,这很棒。但是,当我试图离开那个页面时(当我按下“返回按钮”)并转到上一页时,我收到一个错误。
这是错误:
Setting up AdControlView in UWP throws 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.'.
它被扔在line number 50,在那里我设置了SetNativeControl(adView);
。我现在已经评论过了,但是一旦我对它发表评论,我就会看到这个错误。
有人可以帮我解决这个问题。
在UWP中设置AdControlView会抛出System.InvalidOperationException:'无法在没有Element的情况下分配本机控件;渲染器未绑定和/或处置。请参阅Xamarin.Forms渲染器以获取OnElementChanged的参考实现。
原因是xamarin Element已经释放但SetNativeControl
再次被调用导致本机控件在页面返回时找不到匹配的xamarin元素。所以你可以设置一个标志(isRegist
)来记录注册的广告。
public class AdViewRenderer : ViewRenderer<AdControlView, AdControl>
{
string bannerId = "test";
AdControl adView;
string applicationID = "3f83fe91-d6be-434d-a0ae-7351c5a997f1";
bool isRegist = false;
protected override void OnElementChanged(ElementChangedEventArgs<AdControlView> e)
{
base.OnElementChanged(e);
if (Control == null && isRegist != true)
{
CreateNativeAdControl();
SetNativeControl(adView);
isRegist = true;
}
}
private void CreateNativeAdControl()
{
if (adView != null)
return;
var width = 300;
var height = 50;
if (AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Desktop")
{
width = 728;
height = 90;
}
// Setup your BannerView, review AdSizeCons class for more Ad sizes.
adView = new AdControl
{
ApplicationId = applicationID,
AdUnitId = bannerId,
HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center,
VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Bottom,
Height = height,
Width = width
};
}
}