I have a timer object:
class GameTimer
{
private CancellationTokenSource cancellation;
BindingClass bindingClass;
public GameTimer(BindingClass bindingClass)
{
this.bindingClass = bindingClass;
cancellation = new CancellationTokenSource();
}
public void Start()
{
bindingClass.SecondsElapsed = 20;
CancellationTokenSource cts = cancellation;
Device.StartTimer(new TimeSpan(0, 0, 1), () =>
{
if (cts.IsCancellationRequested) return false;
if (bindingClass.SecondsElapsed > 0)
{
bindingClass.SecondsElapsed--;
}
return true;
});
}
public void Stop()
{
Interlocked.Exchange(ref this.cancellation, new CancellationTokenSource()).Cancel();
}
}
Another object that holds some variables:
public class BindingClass : INotifyPropertyChanged
{
private int _secondsElapsed;
public int SecondsElapsed
{
get { return _secondsElapsed; }
set
{
if (_secondsElapsed != value)
{
_secondsElapsed = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string name = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
And a main page:
public partial class GamePage : ContentPage
{
private int currentSelector;
private int selectorCount = 0;
TapGestureRecognizer tapGestureRecognizer = new TapGestureRecognizer();
Image img;
BindingClass bindingClass;
GameTimer gameTimer;
public GamePage(BindingClass bindingClass)
{
InitializeComponent();
this.bindingClass = bindingClass;
gameTimer = new GameTimer(bindingClass);
gameTimer.Start();
this.BindingContext = this.bindingClass;
NavigationPage.SetHasNavigationBar(this, false);
}
}
What would be the proper to display some sort of alert or at least some event, like after the SecondsElapsed
reaches 0? I tried putting a DisplayAlert
inside set{}
, but it does not show any pop-up:
public class BindingClass : INotifyPropertyChanged
{
private static Page page = new Page();
private int _secondsElapsed;
public int SecondsElapsed
{
get { return _secondsElapsed; }
set
{
if (_secondsElapsed == 0)
{
page.DisplayAlert("AW", "AW", "AW");
}
if (_secondsElapsed != value)
{
_secondsElapsed = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string name = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
I don't know if I can call some functions or fire some event inside BindingClass
.