using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using Xamarin.Forms;
namespace TimerTest
{
public partial class MainPage : ContentPage
{
Label label;
int i = 0;
private static System.Timers.Timer aTimer;
public MainPage()
{
InitializeComponent();
label = new Label
{
Text = ""+i,
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center
};
this.Content = label;
SetTimer();
//this.Content = label;
}
public void SetTimer()
{
// Create a timer with a two second interval.
aTimer = new System.Timers.Timer(2000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
private async void OnTimedEvent(Object source, ElapsedEventArgs e)
{
i++;
label.Text = ""+i;
//this.Content = label;
}
}
}
我已关注微软的然而,当尝试实际实现它时,屏幕上不会更新任何内容。
下面我在 Xamarin.Forms 中设置了一个简单的程序,它应该更新label
计算任何东西i
是每个2 seconds
,但是,屏幕只是位于 0(什么是label
被发起)。
有谁知道我做错了什么以及如何解决我的问题?
提前致谢!
您不在 UI 线程上,因为计时器回调位于后台线程上,请使用Device.BeginInvokeOnMainThread
在这种情况下更新 UI 元素时:
所以当更新你的label
回调中的实例,执行以下操作:
Device.BeginInvokeOnMainThread(() => label.Text = "" +i;);
如果我要更新文本并更新另一个元素,我是否只需在 label.Text = ""+1 之后放置一个 , 或者我是否必须复制整个其他行,
提供给的参数BeginInvokeOnMainThread
is an Action
,因此您可以仅使用一个“块”在 UI 线程上执行所需数量的代码:
Device.BeginInvokeOnMainThread(() =>
{
...;
...;
...;
});
Or:
void UIThreadAction()
{
...;
...;
...;
}
Device.BeginInvokeOnMainThread(UIThreadAction);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)