2

我的应用程序有一个 WebView 用于显示一些联系信息。它有一个网站链接,我想使用Device.OpenUri(). 我正在使用FreshMvvm,我想Navigating在 ViewModel 中拦截来自 WebView 的事件并取消将外部页面加载到 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,而且我不知道如何防止发生默认行为。

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

4

2 回答 2

3

最近重新审视了另一个项目,我偶然发现了答案。更新后的 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
            ));
    }
}
于 2017-03-27T21:56:20.273 回答
0

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

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

于 2017-03-22T09:28:20.910 回答