首页 > 解决方案 > 如何使计时器运行而不冻结页面

问题描述

我正在制作 xamarin 欢迎页面的斜线屏幕页面。

我想实现将SlashScreen在 5 秒后关闭的计时器。并在 xaml 中显示秒数。

<Label TextColor="Black" FontSize= "20"  Text="{Binding timerSecond}"/>

这是我的课:

public partial class SlashScreen : ContentPage
{
    int timerSecond = 5;

    public SlashScreen()
    {
        InitializeComponent();
    }

    protected override void OnAppearing()
    {
        var timer = new System.Timers.Timer(1000);
        timer.Start();
        timer.Elapsed += (obj, args) =>
        {

            if (timerSecond == 0)
            {
                timer.Stop();
                Application.Current.MainPage = new MainPage();
            }
            else
            {
                timerSecond--;
            }
        };

    }
}

谢谢你的帮助。

标签: c#xamarin

解决方案


这未经测试。但它应该适合你

        public partial class SlashScreen : ContentPage
        {
            int _timerSecound = 5;
            public SlashScreen()
            {
                InitializeComponent();
            }

            protected override void OnAppearing()
            {
                Device.StartTimer(TimeSpan.FromSeconds(1), () =>
                {
                        _timerSecound --;
                        timeSecound.Text = _timerSecound.ToString();
                        if (_timerSecound <=0){ 
                        /// your code here, 
                        // i dont know if you could create a new mainpage, this should not work.
                        Application.Current.MainPage = new MainPage();
                        // dont know if this will work for you, but this will close 
                        // the current and go back too the prev screen
                        this.Navigation.PopAsync ();
                        this.Navigation.PopToRootAsync();
                        return false; // stop
                      }
                      return true; // repeat
                };
            }
        }


推荐阅读