Reputation: 527
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
Upvotes: 4
Views: 3149
Reputation: 11105
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");
Upvotes: 3
Reputation: 2855
Your changeURL
method is marked static
, meaning that it cannot use anything that isn't marked static. Learn more about what static means..
Since the class launcher5Page
is a partial class, one imagines that the webview1
variable used in the snippet is defined in the different parts of the class. webview1
is called a member
of class launcher5Page
as it is defined outside of any method, and inside the class.
Your solution: remove the static
keyword from your changeURL
method, or make the webview1
member static
so that other static
members such as changeURL
can use it.
public **partial** class launcher5Page : ContentPage
{
public launcher5Page()
{
InitializeComponent();
webview1.Source = "web address here";
}
public **static** bool changeURL(string urlString)
{
**webview1**.Source = urlString;
return true;
}
}
Also all of this has absolutely nothing to do with Xamarin, other than Xamarin being a set of libraries written in c#. Your problem lies completely in your lack of knowledge of the c# language.
Upvotes: 1