如何在ViewModel中拦截WebView导航事件

如何在ViewModel中拦截WebView导航事件

本文介绍了如何在ViewModel中拦截WebView导航事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序具有一个WebView,用于显示一些联系信息.它具有指向我要使用Device.OpenUri()从外部加载的网站的链接.我正在使用 FreshMvvm ,我想截取在ViewModel中从WebView中删除Navigating事件,并取消将外部页面加载到WebView中的默认操作.

My app has a WebView for displaying some contact information. It has a link to a website that I want to load externally using Device.OpenUri(). I'm using FreshMvvm and I want to intercept the Navigating event from the WebView in the ViewModel and cancel the default action which would load the external page into the WebView.

我尝试使用 Corcav.Behaviors 插件,该插件会调用我的ViewModel命令:

I've tried using the Corcav.Behaviors plugin which does call my ViewModel command:

        <WebView
            HorizontalOptions="Fill"
            VerticalOptions="FillAndExpand"
            Source="{Binding WebViewSource}">
              <b:Interaction.Behaviors>
                <b:BehaviorCollection>
                    <b:EventToCommand
                        EventName="Navigating"
                        Command="{Binding NavigatingCommand}"
                        CommandParameter="{Binding}"/> <!-- what goes here -->
                </b:BehaviorCollection>
              </b:Interaction.Behaviors>
        </WebView>

但是我不确定CommandParameter应该是什么-我需要被点击的链接的URI,而且我不知道如何防止默认行为的发生.

But I'm not sure what the CommandParameter should be - I need the URI of the link that was tapped, and I don't know how to then prevent the default behaviour from occurring.

这是最好的方法还是应该寻找替代方法?

Is this the best approach or should I be looking at an alternative?

推荐答案

最近我又在另一个项目中偶然发现了这个问题,我偶然发现了答案.更新的XAML是:

Having revisited this recently for another project I stumbled across the answer. The updated XAML is:

<WebView
    x:Name="webView"
    HorizontalOptions="Fill"
    VerticalOptions="FillAndExpand"
    Source="{Binding WebViewSource}">
    <behaviors:Interaction.Behaviors>
        <behaviors:BehaviorCollection>
            <behaviors:EventToCommand
                EventName="Navigating"
                Command="{Binding NavigatingCommand}"
                PassEventArgument="True" />
        </behaviors:BehaviorCollection>
    </behaviors:Interaction.Behaviors>
</WebView>

在设备浏览器中打开链接之前,ViewModel中将已点击网址与有效选项列表相匹配的代码为:

The code in the ViewModel, that matches the tapped url against a list of valid options before opening the link in the device's browser, is:

public Command<WebNavigatingEventArgs> NavigatingCommand
{
    get
    {
        return navigatingCommand ?? (navigatingCommand = new Command<WebNavigatingEventArgs>(
            (param) =>
            {
                if (param != null && -1 < Array.IndexOf(_uris, param.Url))
                {
                    Device.OpenUri(new Uri(param.Url));
                    param.Cancel = true;
                }
            },
            (param) => true
            ));
    }
}

这篇关于如何在ViewModel中拦截WebView导航事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 20:05