How to get Navigating event of WebView in ViewModel in Xamarin.Forms ??

i want to get Navigating event of WebView in ViewModel in Xamarin.Forms. Please tell me how i can achieve it ??

Answers

  • yelinzhyelinzh Member, Xamarin Team Xamurai
    edited April 30

    Try to use Corcav.Behaviors plugin. The plugin can easily help you binding the Navigating Event to ViewModel.
    page.xaml

    <WebView HeightRequest="800" 
                         WidthRequest="800"
                         Source="https://www.google.com"
                         >
        <behaviors:Interaction.Behaviors>
            <behaviors:BehaviorCollection>
                <behaviors:EventToCommand 
                    EventName="Naviating"
                    Command="{Binding navigatingCommand}"
                    PassEventArgument="True"
                    />
            </behaviors:BehaviorCollection>
        </behaviors:Interaction.Behaviors>
    </WebView>
    

    ViewModel.cs

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

    Check the link: https://stackoverflow.com/questions/36560415/how-to-intercept-webview-navigating-event-in-viewmodel
    Sample here: https://github.com/corradocavalli/Corcav.Behaviors

  • XamtasticXamtastic Member ✭✭✭

    I think you're looking for the "Navigated" and that should be MVVM safe

Sign In or Register to comment.