【发布时间】:2018-01-24 05:46:27
【问题描述】:
主页
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 运行时,CurrentSeconds 中的 set{} 也会触发。但问题是,set{} 内部的DisplayAlert 根本不会触发,只有btnSample_Clicked 内部的DisplayAlert。
如何在set{} 中也触发DisplayAlert?或者如果不可能,有没有办法从 GlobalVariables 触发 Start Page 中的事件?
【问题讨论】:
标签: c# xamarin xamarin.forms