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

时间:2018-12-15 04:05:36

标签: c# xamarin xamarin.forms

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的定义来实现计时器方法,但是,当尝试实际实现它时,屏幕上什么也没有更新。

下面,我在Xamarin中设置了一个简单的程序。该窗体应将label更新为每个i的{​​{1}}的计数,但是屏幕仅位于0 (2 seconds的初始化对象。)

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

谢谢!

1 个答案:

答案 0 :(得分:3)

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

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

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

如果我要更新文本并更新另一个元素,我会在label.Text =“” +1后面放置一个,还是要复制另一行?

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

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

或者:

void UIThreadAction()
{
    ...;
    ...;
    ...;
}
Device.BeginInvokeOnMainThread(UIThreadAction);