如何在不冻结的情况下使计时器运行

时间:2019-02-17 05:56:41

标签: c# xamarin

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

我想实现一个计时器,它将在5秒后关闭SlashScreen。 并在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--;
            }
        };

    }
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这未经测试。但它应该对您有用

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