Matthew Matthew - 2 months ago 39
C# Question

Xamarin - WebView update URL from another page/view

I have a very basic tabbed application
On page one is a web view using Xamarin.Forms

<WebView x:Name="webview1" IsVisible="true" Source="" ></WebView>


I can update the URL of this view from the .cs code behind using for example

webview1.Source = "http://www.microsoft.com"


I have a second tab which I'm using for settings/additional info.
On this second page I have a button which on click I want to reset the web view on Page 1 to a new Url / updates the Source.

Just trying to reference it on second page tells me I can't due to protection level and an object reference for a static item is required.

updated:

public partial class launcher5Page : ContentPage
{
public launcher5Page()
{
InitializeComponent();

webview1.Source = "web address here";
}

public static bool changeURL(string urlString)
{
webview1.Source = urlString;
return true;
}
}


Still getting
Error CS0120: An object reference is required to access non-static member

Answer

I would suggest using the MessagingCenter for such a job. Then you could do this:

public partial class launcher5Page : ContentPage {

    public launcher5Page() {
        InitializeComponent();

        webview1.Source = "web address here";

        /* Normally you want to subscribe in OnAppearing and unsubscribe in OnDisappearing but since another page would call this, we need to stay subscribed */
        MessagingCenter.Unsubscribe<string>(this, "ChangeWebViewKey");
        MessagingCenter.Subscribe<string>(this, "ChangeWebViewKey", newWebViewUrl => Device.BeginInvokeOnMainThread(async () => {
            webview1.Source = newWebViewUrl;
        }));
    }
}

Then on your other page:

 Xamarin.Forms.MessagingCenter.Send("https://www.google.com", "ChangeWebViewKey");