How to access to the “Reload” method of a WebView from a ViewModel? RRS feed

  • Question

  • User167645 posted


    I'm working on a Xamarin.Forms app that contains a WebView allowing users to schedule an appointment: <WebView x:Name="webView" Source="{Binding UrlBooking}" WidthRequest="1000" HeightRequest="1000" />

    I would like to use use a ToolbarItem to reset/reload the WebView.

    I'm able to achieve this in the code-behind with: this.webView.Reload();

    But I don't see how to this with a Command in the ViewModel. Is it possible to do this?

    Tuesday, September 8, 2020 1:00 PM

All replies

  • User53115 posted

    I'm not actually a big fan of this pattern, but you could define the command in your code-behind and inject it into your ViewModel.

    Page.xaml: <ToolbarItem Command="{Binding RefreshCommand}"/>

    Page.xaml.cs: ``` public MyPage() { InitializeComponent();

    var viewModel = new MyViewModel();
    viewModel.RefreshCommand = new Command(ReloadWebView);
    BindingContext = viewModel;


    private void ReloadWebView() { this.webView.Reload(); } ```

    ViewModel.cs: private ICommand _refreshCommand; public ICommand RefreshCommand { get => _refreshCommand; set { _refreshCommand = value; OnPropertyChanged(); } }

    Tuesday, September 8, 2020 10:03 PM
  • User76049 posted

    There is no nice way if the control isn't MVVM friendly....like this pretty poor control.

    ``` protected override void OnBindingContextChanged() { base.OnBindingContextChanged();

            if (BindingContext is MyViewModel viewModel)
                _viewModel = viewModel;
                _viewModel.PropertyChanged += OnViewModelPropertyChanged;
           // You have to unhook this event handler to prevent a memory leak
        private void OnViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
            switch (e.PropertyName)
                case nameof(_viewModel.PropertyIWantToListenTo):


    Wednesday, September 9, 2020 12:12 AM