C#Xamarin计时器类未更新视图

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

我已经遵循了Microsoft’s的定义来实现timer方法,但是,当尝试实际实现它时,没有任何内容更新到屏幕上.

下面我在Xamarin中设置了一个简单的程序.Forms应该每2秒将标签更新为i的计数,但是屏幕只是位于0(标签被初始化到的位置)上.

有谁知道我在做什么错以及如何解决我的问题?

提前致谢!

解决方法:

您不在UI线程上,因为Timer回调在后台线程上,请在这种情况下更新UI元素时使用Device.BeginInvokeOnMainThread:

因此,在回调中更新标签实例时,请执行以下操作:

Device.BeginInvokeOnMainThread(() => label.Text = "" +i;);

If I were to update the text and update another element, would I just place a , after label.Text = “”+1or would I have to have a whole other line replicated,

提供给BeginInvokeOnMainThread的参数是一个Action,因此您可以仅使用一个“块”在UI线程上执行所需的代码:

Device.BeginInvokeOnMainThread(() =>
{
    ...;
    ...;
    ...;
});

要么:

void UIThreadAction()
{
    ...;
    ...;
    ...;
}
Device.BeginInvokeOnMainThread(UIThreadAction);
上一篇:Xamarin Forms:如何在Android中更改工具栏高度?


下一篇:我如何在iOS / Android上获得当前的设备语言?