How to intercept WebView Navigating event in ViewModel

别来无恙 提交于 2019-12-02 04:08:50
David Clarke

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>

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

You can´t navigate with a WebView, you must use a custom render (hybridwebview). Here is an explanation:

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!