为什么不能在应用程序的另一个类中调用此公共方法?

时间:2018-09-09 18:10:51

标签: c# xamarin xamarin.forms

我添加了一个公共方法来返回变量pageLoaded,但是Visual Studio显示此错误“方法MainPage.PageLoaded()所需的对象引用不是静态的”。逻辑是仅在pageLoaded为true时才完成Splash Activiy。如果有人对此有更好的主意,那我将很高兴知道,我才刚刚开始学习C#/ Xamarin。

我的代码:

namespace MyApp
{
    public partial class MainPage : ContentPage
    {
        private bool pageLoaded = false;
        public MainPage()
        {
            InitializeComponent();
            webnav.HeightRequest = 1000;
            webnav.WidthRequest = 1000;
            webnav.Source = "https://www.example.com";
        }

        public void Webnav_Navigated(object sender, WebNavigatedEventArgs e)
        {
            pageLoaded = true;
        }

        public bool PageLoaded()
        {
            return pageLoaded;
        }
    }
}

代码2:

...
...
using MyApp;
namespace MyApp.Droid
{
    [Activity(Label = "My App", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
            while (true)
            {
                if (MainPage.PageLoaded())
                {
                    SplashScreen.fa.Finish();
                    break;
                }
            }
        }
   }
}

2 个答案:

答案 0 :(得分:1)

问题:

您的.PageLoaded()方法是 instance方法。它只能在类型为MainPage的实例化对象上调用

您在初始屏幕中对它的引用正在尝试将其作为静态方法调用,这有两个问题:

  1. 如上所述,您没有使用the static keyword
  2. 进行定义
  3. 即使您将其定义为静态,也不会告诉您有关正在加载的真实页面的任何信息

解决方案:

不要这样做。从知道何时已加载的页面实例控制初始屏幕的可见性。在MainPage

中创建和引用初始屏幕

编辑:

要进一步阐明区别:

// calling a method against the static definition of the class
MainPage.PageLoaded();
// calling a method against an instance of the class
new MainPage().PageLoaded();

以上代码不是解决方案,而是实例方法与静态方法之间差异的示例。 您的 PageLoaded方法不应是静态的,因为您到目前为止已将所有内容都布置了。

答案 1 :(得分:-3)

由于MainPage类不是静态的,因此您需要创建MainPage类的对象,并使用该对象从该类中调用方法。

相关问题