A slightly different problem is to repeat an action multiple times in a fixed interval. As indicated in the previous section, Device.StartTimer is capable of doing so.
To demonstrate the use of repeating actions, we create a “Count down” button.
var button = new Button {
Text = "Count down",
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.CenterAndExpand,
};
When pressing the button, it will count down from 3 to 0. First, we set the Text to “3”. Then we start a timer with an interval of one second. In each iteration, it sets the current number by parsing the Button.Text and subtracting 1. While the number is larger than zero, the timer continues.
button.Command = new Command(o => {
button.Text = "3";
Device.StartTimer(TimeSpan.FromSeconds(1), () => {
var number = float.Parse(button.Text) - 1;
button.Text = number.ToString();
return number > 0;
});
});
Finally, we place the button on our MainPage.
MainPage = new ContentPage { Content = button };