DisplayAlert在变量变化期间不显示

时间:2018-01-24 05:46:27

标签: c# xamarin xamarin.forms

主页

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        NavigationPage.SetHasNavigationBar(this, false);
        btnStartGame.Clicked += btnStartGame_Clicked;
    }
    public async void btnStartGame_Clicked(object sender, EventArgs e)
    {
        GlobalVariables globalVar = new GlobalVariables();
        globalVar.CurrentSeconds = 20;
        StartPage startPage = new StartPage();
        startPage.setGlobalVariables(globalVar);
        await Navigation.PushAsync(startPage);
    }
}

起始页

public partial class StartPage : ContentPage
{
    GlobalVariables globalVar;
    public StartPage()
    {
        InitializeComponent();
        this.BindingContext = globalVar;
        NavigationPage.SetHasNavigationBar(this, false);
    }
    public void setGlobalVariables(GlobalVariables globalVar)
    {
        this.globalVar = globalVar;
    }
    private void btnSample_Clicked(object sender, System.EventArgs e)
    {
        globalVar.CurrentSeconds++;
        DisplayAlert("AW", globalVar.CurrentSeconds.ToString(), "AW");
    }
}

GlobalVariables.cs

public class GlobalVariables : INotifyPropertyChanged
{
    private int _currentSeconds;
    public int CurrentSeconds
    {
        get { return _currentSeconds; }
        set
        {
            if (_currentSeconds != value)
            {
                _currentSeconds = value;
                Device.BeginInvokeOnMainThread(async () =>
                {
                    await FingerSmash2.App.Current.MainPage.DisplayAlert("AW", "AW", "AW");
                });
            }
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName] string name = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}

使用此代码,每次btnSample_Clicked运行时,set{}中的CurrentSeconds也会触发。但问题是,DisplayAlertset{}根本不会触发,DisplayAlertbtnSample_Clicked

如何同时触发DisplayAlert内的set{}?或者,如果不可能,有没有办法从 GlobalVariables 起始页中触发事件?

1 个答案:

答案 0 :(得分:1)

您的代码似乎没问题。

Xamarin Live Player iOS DisplayActionSheet/Alert所述,它可能与 Xamarin Live Player 有关。

在设备甚至模拟器上部署您的应用应该确保您的代码是否正确!