【发布时间】:2022-01-06 03:20:00
【问题描述】:
所以我已经在代码中完成了这个:
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 in为了隐藏它。如果您能解释界面及其事件的工作原理,我将非常感谢。
【问题讨论】:
-
什么是异常/错误消息?
-
您可能需要使用
Dispatcher更改Text属性的值,否则绑定在错误的线程上运行,也许是ThreadPool? Timer documentation。可以通过将 Timer 的 SynchronizingObject 设置为this来缓解?
标签: c# xamarin xamarin.forms