倒数计时器system.timers问题Xamarin形式

问题描述

现在我更新了代码,即时消息未收到错误,问题是它没有计数

   private System.Timers.Timer _timer;
    private int _countSeconds;
    public MainPage()
    {
        InitializeComponent();
        _timer = new System.Timers.Timer();
        _timer.Interval = 1000;
        _timer.Elapsed += _timer_Elapsed;
        _countSeconds = 5;
        _timer.Enabled = true;
    }
                          
    private void _timer_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
    {
        _countSeconds--;
        CountLabel.Text = _countSeconds.ToString();

        if (_countSeconds == 0)
        {
            _timer.Stop();
        }
        throw new NotImplementedException();
        
       
    }
                     
    }
}

我认为它与OnTimedEvent方法有关,我在调用它时需要指定参数。我只是不知道要传入什么,但是我希望从按钮中调用它,但是不知道什么是系统计时器elapsedeventargs e。看过youtube,reddit,stackoverflow和microsoft。在任何地方都没有真正的解释或帮助。

在这里我的MainPage.xaml

<Label Text="Count" x:Name="CountLabel"  HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontSize="Large"></Label>

解决方法

您可以使用Device.Timer代替Xamarin.Forms中的System.Timers。

public partial class MainPage : ContentPage
{
    private int _countSeconds  = 5 ;

    public MainPage()
    {
        InitializeComponent();

        Device.StartTimer(TimeSpan.FromSeconds(1),() =>
         {
             _countSeconds--;
             CountLabel.Text = _countSeconds.ToString();
             return Convert.ToBoolean(_countSeconds);
         });
    }

我认为此问题和解答对您有所帮助。 How do I add a timer in Xamarin?

,

Visual Studio通常可以帮助编写事件处理程序方法。输入“ + =”后,按TAB键一次或两次。但是这些方法似乎是正确的。 –迈克尔

您需要在主线程上更新标签-请参阅docs.microsoft.com/en-us/xamarin/essentials/main-thread – Jason