c# - 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();
}
}
}
解决方案
UI 更新只能在主线程上完成
Device.BeginInvokeOnMainThread( () => {
label_timer.Text = time;
});
推荐阅读
- sass - How to add text to the image slider (carusel) sass/html (react)
- python - Pyspark - Selecting rows in dataframe based on values that exist in another dataframe
- javascript - fs.createReadStream vs Readable 用于重文件
- ruby-on-rails - aws-cdk:对于 Web 应用程序的文件夹结构有什么好的指南或建议吗?
- python - I want to find the sum of squares of digits in a number, my code work fine for positive numbers but doesn't seem to work with negative numbers
- anylogic - seizeTransporter Block out port stop working
- python - How to overcome the aspect ratio warnings when plotting images in log-scaled axis with Python?
- javascript - Parsing through a column of a csv file and save it to arrays in javascript to run a matching between rows of the selected column
- elasticsearch - Elasticsearch 7 x_content_parse_exception failed to parse field [must]
- python-3.x - How can we get disk usage details(total,free,used) from ec2 instance using boto3?