【问题标题】:How to intercept WebView Navigating event in ViewModel如何在 ViewModel 中拦截 WebView 导航事件
【发布时间】:2016-08-02 07:22:04
【问题描述】:

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

我尝试过使用 Corcav.Behaviors 插件,它确实调用了我的 ViewModel 命令:

        <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,但我不知道如何防止发生默认行为。

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

【问题讨论】:

  • 不需要指定CommandParameter,NavigatingCommand应该是DelegateCommand类型,tappedItem是参数的item属性。
  • @rauland 当我使用这种方法时,即省略 CommandParameter,我没有得到任何作为参数传递的信息 - 即使将 object 指定为参数类型。

标签: xamarin.forms freshmvvm


【解决方案1】:

最近为了另一个项目重新访问了这个,我偶然发现了the answer。更新后的 XAML 是:

<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 中的代码是:

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
            ));
    }
}

【讨论】:

    【解决方案2】:

    您不能使用 WebView 进行导航,您必须使用自定义渲染(混合网络视图)。 这是一个解释:

    https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/custom-renderer/hybridwebview/

    【讨论】:

    • 也许你误解了我想要达到的目标。我想拦截在点击 WebView 中的链接时触发的 Navigating 事件,然后在外部浏览器中打开关联的 URL。我没有尝试使用该链接在应用内导航。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多