所以我在代碼中做到了這一點:
public partial class Timer : ContentView , INotifyPropertyChanged
{
private int seconds = 30;
private System.Timers.Timer timer;
public Timer()
{
InitializeComponent();
timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.AutoReset = true;
timer.Elapsed = new System.Timers.ElapsedEventHandler(OneSecondPassed);
timer.Enabled = true;
}
private void OneSecondPassed(object source, System.Timers.ElapsedEventArgs e)
{
seconds--;
Time = seconds.ToString();
}
public event PropertyChangedEventHandler PropertyChanged;
public string Time
{
get => seconds.ToString();
set
{
Time = value;
if (PropertyChanged != null)
{
PropertyChanged(this , new PropertyChangedEventArgs("Time"));
}
}
}
}
然后在 XAML 中將我的標簽文本系結到它:
<Label BindingContext ="{x:Reference this}"
Text="{Binding Time}"/>
當我啟動應用程式時,它崩潰了......我真的不明白 PropertyChanged 是如何作業的,只是 INotifyPropertyChanged 實作了它。另外,當我宣告 PropertyChanged 時,它告訴我 BindableObject.PropertyChanged 已經存在,使用 new 來隱藏它。如果你能解釋一下界面和它的事件是如何作業的,我會非常感激。
uj5u.com熱心網友回復:
你的二傳手正在創建一個無限回圈。
set
{
// this will call the setter again, infinitely
Time = value;
...
}
你已經有一個私有變數seconds,你應該在這里使用它
public int Time
{
get => seconds;
set
{
seconds = value;
if (PropertyChanged != null)
{
PropertyChanged(this , new PropertyChangedEventArgs("Time"));
}
}
}
private void OneSecondPassed(object source, System.Timers.ElapsedEventArgs e)
{
Time--;
}
uj5u.com熱心網友回復:
當我宣告 PropertyChanged 時,它告訴我 BindableObject.PropertyChanged 已經存在
我看到Timer繼承自ContentView.
ContentView是 a BindableObject,因此它已經實作了系結中使用的所有內容,例如 PropertyChanged。洗掉您的宣告PropertyChanged。
可選:您也可以洗掉, INotifyPropertyChanged-ContentView為您執行此操作。然而,把它留在那里是無害的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/371646.html
標籤:C# 沙马林 xamarin.forms
