c# - Xamarin - 来自另一个页面/ View 的 WebView 更新 URL

标签 c# xamarin xamarin.forms

我有一个非常基本的选项卡式应用程序 第一页是使用 Xamarin.Forms 的 Web View

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

我可以使用例如后面的​​ .cs 代码更新此 View 的 URL

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

我有第二个选项卡,用于设置/附加信息。 在第二页上,我有一个按钮,单击该按钮我想将第 1 页上的 Web View 重置为新的 Url/更新源。

只是试图在第二页上引用它告诉我我不能,因为保护级别和静态项目的对象引用是必需的。

更新:

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

        webview1.Source = "web address here";
    }

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

还在继续 错误 CS0120:需要对象引用才能访问非静态成员

最佳答案

我建议使用 MessagingCenter 来完成这样的工作。然后你可以这样做:

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

然后在你的其他页面上:

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

关于c# - Xamarin - 来自另一个页面/ View 的 WebView 更新 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39704288/

相关文章:

c# - 将代码标记为在设计时不运行

xamarin.forms - Xamarin 形式的流畅设计

android - Xamarin 视频播放器组件在 Android 上拉伸(stretch)视频

c# - Xamarin.Mac - 发送通知

ios - Xamarin - 获取保存到照片库的图像的文件路径

c# - Xamarin Forms 在 Webview 导航问题中处理超链接

c# - 带有 Datagrid 的窗口上的 ShowDialog() 抛出除零错误

c# - 有效的 C# 二维列表

c# - 将 Monotouch 与 Google .NET API 结合使用

C# - 俄罗斯方 block 克隆 - 无法阻止正确响应箭头键组合