[英]Displaying time on multiple Xamarin.Forms views
我有一个Xamarin.Forms应用程序,该应用程序的页面都使用ControlTemplate来实现自定义标头。 在页眉中,某些页面(以及相应的ControlTemplates)具有时间标签,该标签通过ViewModel中的计时器(带有绑定)进行更新。
我目前正在做的是在每个ViewModel上实现时间功能。 是否有一个很好的方法可以在一处实现此功能,并以最少的样板代码在任何地方使用它? 我考虑过要在App.xaml.cs中实现计时器,但是我仍然必须以某种方式通知每个视图模型。 我只是无法提出一个优雅的解决方案。
因为没有代码,所以很难说出合适的解决方案,但是您可以使用基础ViewModel并从中继承吗?
或者,就像您自己说的那样,在App.xaml.cs中有一个,您可以通过Messaging Center进行更新 ,或者实现自己的事件,该事件在每个时间间隔触发并从ViewModels中插入。
这是我的解决方案。 它使用.NET标准库而不是PCL。 您需要System.Threading.Timer的.NET Standard,否则,您需要使用Xamarin.Forms Timer或3rd party实现。
public partial class App : Application
{
private Timer timer;
private AutoResetEvent autoEvent = new AutoResetEvent(false); // Configures the state of the event
public App()
{
this.InitializeComponent();
// Start timer
this.timer = new Timer(this.CheckTime, this.autoEvent, 1000, 60000);
}
// ViewModels will subscribe to this
public static event EventHandler<TimeEventArgs> TimeEvent;
// The TimerCallback needed for the timer. The parameter is not practically needed but needed for the TimerCallback signature.
private void CheckTime(object state) =>
this.OnRaiseTimeEvent(new TimeEventArgs(DateTime.Now.ToString("HH:mm")));
// Invokes the event
private void OnRaiseTimeEvent(TimeEventArgs e) =>
TimeEvent?.Invoke(this, e);
}
在ViewModel中
public class ViewModel : BaseViewModel
{
private string time;
public ViewModel()
{
// Subscribes to the event
App.TimeEvent += (object o, TimeEventArgs e) =>
{
this.Time = e.Time;
};
}
// Bind to this in your view
public string Time
{
get => this.time;
set => this.SetProperty(ref this.time, value);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.