首页 > 解决方案 > Labell.Text 只会更新一次

问题描述

我正在运行计时器并计算时间。计时器以按钮开始,标签显示时间。至少这是计划。但是运行代码,label.Text 只会更新一次。它从 6:00 开始,到 5:59 会打勾一次,然后会冻结为什么会发生这种情况?

我花了很多时间试图了解发生了什么。变量 time 正在改变,而 label.Text 没有。难道我做错了什么?

public partial class Running : ContentPage
{
    Timer timer;
    double seconds = 360;

    public Running()
    {
        InitializeComponent();
        button_run.Clicked += Button_Run_Clicked;
    }

    void Button_Run_Clicked(object sender, EventArgs e)
    {
        if (button_run.Text == "Start!")
        {
            button_run.Text = "Stop";
            timer = new Timer();
            timer.Interval = 100; // 100 milliseconds  
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
        }

        else
        {
            button_run.Text = "Start!";
        }


    }

    private void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        seconds -= 0.1;
        int minutes = (int)seconds / 60;
        int secs = (int)seconds % 60;
        string time = minutes.ToString() + ":" + secs.ToString();
        label_timer.Text = time; // the string time is changing!

        if (minutes != 0)
        {
            timer.Start();
        }
        else
        {
            timer.Stop();
        }
    }
}

标签: c#xamarin

解决方案


UI 更新只能在主线程上完成

Device.BeginInvokeOnMainThread( () => {
  label_timer.Text = time;
});

推荐阅读