Xamarin:OnTimedEvent()不发射(定时器)

时间:2017-10-17 12:51:55

标签: c#

我这样做了x次,但今天它决定不去工作。也许我已经失明了?简单的代码:

    private TextView txt;
    private Timer _timer;
    private int seconds; 

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView (Resource.Layout.Main);
        txt = FindViewById<TextView>(Resource.Id.testTextView);
        seconds = 0;
        Timer();
    }

    void Timer()
    {
        _timer = new System.Timers.Timer();
        _timer.Interval = 100;
        _timer.Elapsed += OnTimedEvent;
        _timer.Enabled = true;
        _timer.Start();
    }

    private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
    {
        seconds += 1;
        CountDown(); 
    }

    void CountDown()
    {
        txt.Text = seconds.ToString();
    }

但是OnTimedEvent没有被调用。决不。为什么?!

1 个答案:

答案 0 :(得分:0)

谢谢大家,我发现了: 计时器工作,但我无法从非ui线程更改UI元素。除非我这样做:

        RunOnUiThread(() => txt.Text = seconds.ToString());

然后我们去:)