主页
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
也会触发。但问题是,DisplayAlert
内set{}
根本不会触发,DisplayAlert
内btnSample_Clicked
。
如何同时触发DisplayAlert
内的set{}
?或者,如果不可能,有没有办法从 GlobalVariables 起始页中触发事件?
答案 0 :(得分:1)
您的代码似乎没问题。
如Xamarin Live Player iOS DisplayActionSheet/Alert所述,它可能与 Xamarin Live Player 有关。
在设备甚至模拟器上部署您的应用应该确保您的代码是否正确!