如何在Xamarin项目中的类之间进行通信?

oipij1gg  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(54)

我有两个类,一个是秒表类,另一个是生命周期事件类“App”
分类1:

public partial class Stopwatch : ContentPage
    {
        Stopwatch stopwatch;
        bool isOn = false;
        public Stopwatch()
        {
            InitializeComponent();
            stopwatch = new Stopwatch();
            labeltimer.Text = "00:00:00.00";
        }

        private void btnTimerReset(object sender, EventArgs e)
        {
            btnStart.Text = "Start";
            stopwatch.Reset();
        }

        private void btnTimerstop(object sender, EventArgs e)
        {
            if (labeltimer.Text != "00:00:00.00")
                btnStart.Text = "Resume";
            stopwatch.Stop();
        }

        private void btnTimerStart(object sender, EventArgs e)
        {
            Timerstart();
            isOn = true;
        }

        private void Timerstart()
        {
            stopwatch.Start();
            Device.StartTimer(TimeSpan.FromMilliseconds(1), () =>
            {
                labeltimer.Text = stopwatch.Elapsed.ToString("hh\\:mm\\:ss\\.ff");
                return true; // return true to repeat counting, false to stop timer
            });
        }
       public bool isStopwatchEnabled()
        {

            if(isOn)
            {
                return true;
            }
            else
            return false;
        }
    }
}

字符串
App类别

public partial class App : Application
    {
        bool isenableSW = false;
        public App()
        {
            InitializeComponent();

            DependencyService.Register<MockDataStore>();
            MainPage = new AppShell();
            {
                
            };
        }
        protected override void OnSleep()
        {

            Stoppuhr tp = new Stoppuhr();
             isenableSW = tp.isStopwatchEnabled();

            if (isenablesw)
            {
                
                tp.Timerstart();

               
            }
        }
    }


现在我的问题是,当我启动秒表时,我的bool变量从false切换到true。这就是我想要的.当我现在触发onSleep()函数时,它创建了我的秒表类的一个新示例,接下来它应该检查秒表是否在onSleep()触发之前启用,但是我的bool变量总是false,因为它有它的标准值(= false)。这是有道理的.但是我如何在这些类之间正确地通信呢?

tvmytwxo

tvmytwxo1#

我想我找到了一个解决方案。当我这样做时,值不会改变:

bool isOn = false -> static bool isOn = false;

字符串

相关问题