1

Now i updated the code and im not getting errors, problem is its not counting

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

I think it has something to do with the OnTimedEvent method i need to specify arguments when calling it. I just dont know what to pass in but i would like it to be called from a button but no clue what system timers elapsedeventargs e is. Looked on youtube, reddit, stackoverflow and microsoft. No real explanation or help anywhere.

Heres my MainPage.xaml

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

2 Answers2

2

You can use Device.Timer instead of System.Timers in Xamarin.Forms.

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

I think this question and answers help you. How do I add a timer in Xamarin?

-1

Visual Studio can typical help writing event handler methods. After typing `+=´ press TAB once or twice. But the methods seems correct. – Michael

you need to update your Label on the main thread - see learn.microsoft.com/en-us/xamarin/essentials/main-thread – Jason