我正在制作一個健身應用程式,所以我需要一個計時器。我在代碼隱藏中完成了這項作業:
public partial class Timer : ContentView
{
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--;
}
public string Time
{
get => seconds.ToString();
}
}
然后對于 UI,我制作了一個標簽并將其 text 屬性系結到我的 Time 屬性:
<Label BindingContext ="{x:Reference this}"
Text="{Binding Time}"/>
//"this" is a reference to my class
當我啟動應用程式時,計時器保持 30。我知道“秒”肯定會減少,所以系結肯定有問題。我知道我可以在 OneSecondPassed 中更新標簽的 text 屬性,但是我想了解有關資料系結的更多資訊。幫助?
uj5u.com熱心網友回復:
正如杰森所說,實作INotifyPropertyChanged介面是一個不錯的選擇。
為了大家更好的理解,我寫了一個滿足你要求的可運行專案供大家參考。
這是xaml代碼:
<StackLayout>
<Label Text="{Binding DateTime}"
FontSize="Large"
HorizontalOptions="Center"
VerticalOptions="Center"/>
</StackLayout>
這是cs代碼:
public partial class MainPage : ContentPage, INotifyPropertyChanged
{
int dateTime;
public event PropertyChangedEventHandler PropertyChanged;
public MainPage()
{
InitializeComponent();
this.DateTime = 30;
Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
if (DateTime > 0)
{
DateTime--;
}
return true;
});
BindingContext = this;
}
public int DateTime
{
set
{
if (dateTime != value)
{
dateTime = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("DateTime"));
}
}
}
get
{
return dateTime;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/369708.html
上一篇:如何向網格窗格添加邊
