How to intercept WebView Navigating event in ViewModel

后端 未结 2 1041
醉话见心
醉话见心 2021-01-22 03:09

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

相关标签:
2条回答
  • 2021-01-22 03:32

    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
                ));
        }
    }
    
    0 讨论(0)
  • 2021-01-22 03:50

    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/

    0 讨论(0)
提交回复
热议问题