【问题标题】:Lablel.Text will only update once [duplicate]Label.Text 只会更新一个[重复]
【发布时间】:2019-01-17 04:16:16
【问题描述】:

我正在运行计时器并计算时间。计时器以按钮开始,标签显示时间。至少这是计划。 但是运行代码,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


【解决方案1】:

UI 更新只能在主线程上进行

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

【讨论】:

    猜你喜欢
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    相关资源
    最近更新 更多