单击UWP中的Microsoft广告时如何获取事件

时间:2018-07-20 04:01:14

标签: uwp windows-store-apps uwp-xaml advertising

我正在将Microsoft Advertising SDK用于xaml。而且我的应用现在可以展示广告了。但是我想知道用户点击广告时发生的事件。

以下事件均无效。

    <ads:AdControl x:Name="adAd" Grid.Row="3" ApplicationId="" AdUnitId=""
         Width="300" Height="250" AdRefreshed="OnAdRefreshed" 
         ErrorOccurred="OnErrorOccurred"
         Tapped="OnAdTapped" OnPointerDown="OnAdPointerDown" 
         PointerPressed="OnAdPointerPressed"/>

enter image description here

1 个答案:

答案 0 :(得分:1)

  

以下事件均无效。

实际上,您不能直接使用上述事件,因为在广告WebView中显示的超链接单击将忽略该事件。 enter image description here

如果要检测AdControl的点击事件,则可以使用一些间接方法,该方法使用VisualTreeHelper来获取广告WebView并监听其NavigationStarting事件

public static T MyFindListBoxChildOfType<T>(DependencyObject root) where T : class
{
    var MyQueue = new Queue<DependencyObject>();
    MyQueue.Enqueue(root);
    while (MyQueue.Count > 0)
    {
        DependencyObject current = MyQueue.Dequeue();
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(current); i++)
        {
            var child = VisualTreeHelper.GetChild(current, i);
            var typedChild = child as T;
            if (typedChild != null)
            {
                return typedChild;
            }
            MyQueue.Enqueue(child);
        }
    }
    return null;
}


private void AdTest_AdRefreshed(object sender, RoutedEventArgs e)
{
    var ADWebView = MyFindListBoxChildOfType<WebView>(AdTest);
    ADWebView.NavigationStarting += ADWebView_NavigationStarting;
}

private void ADWebView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
    System.Diagnostics.Debug.WriteLine("AD clicked---------------");
}

为避免干扰页面导航,请使用NavigationStarting替代方法退订OnNavigatedFrom

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    base.OnNavigatedFrom(e);
    ADWebView.NavigationStarting -= ADWebView_NavigationStarting;
}