uwp点击微软广告时如何获取事件

How to get the event when clicking the microsoft ad in uwp

我正在为 xaml 使用 Microsoft Advertising SDK。我的应用现在可以显示广告了。但是我想知道用户点击广告时发生的事件。

None 以下事件有效。

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

None of the following event worked.

实际上,您不能直接使用上述事件,因为它会被广告中显示的超链接点击忽略WebView

如果你想检测 AdControl 的点击事件,你可以使用一些间接的方法,使用 VisualTreeHelper 来获取 AD 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---------------");
}

为了避免页面导航的干扰,请在OnNavigatedFrom覆盖方法中取消订阅NavigationStarting

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