首页 > 解决方案 > 倒数计时器 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>

标签: c#androidxamarinxamarin.forms

解决方案


您可以在 Xamarin.Forms 中使用Device.Timer而不是 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);
         });
    }

我认为这个问题和答案对你有帮助。 如何在 Xamarin 中添加计时器?


推荐阅读