在set {}中调用一些事件

时间:2018-01-22 09:16:43

标签: c# xamarin xamarin.forms

我有一个计时器对象:

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

另一个包含一些变量的对象:

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

主页:

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

SecondsElapsed达到0之后显示某种警报或至少某些事件是什么样的?我尝试在DisplayAlert内加set{},但它没有显示任何弹出窗口:

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

我不知道是否可以在BindingClass内调用某些函数或触发某些事件。

0 个答案:

没有答案