C# 在多个Xamarin.Forms视图上显示时间
我有一个Xamarin.Forms应用程序,其中的页面都使用ControlTemplate实现自定义标题。在页眉中,一些页面(因此也包括ControlTemplates)有一个时间标签,该标签在ViewModel中通过计时器(绑定)进行更新C# 在多个Xamarin.Forms视图上显示时间,c#,mvvm,xamarin.forms,C#,Mvvm,Xamarin.forms,我有一个Xamarin.Forms应用程序,其中的页面都使用ControlTemplate实现自定义标题。在页眉中,一些页面(因此也包括ControlTemplates)有一个时间标签,该标签在ViewModel中通过计时器(绑定)进行更新 我目前正在做的是在每个ViewModel上实现时间功能。有没有一种好的方法可以在一个地方实现它,并在任何地方使用它,只需要最少的样板代码?我曾考虑在App.xaml.cs中实现计时器,但我仍然必须以某种方式通知每个viewmodel。我就是想不出一个优雅的解
我目前正在做的是在每个ViewModel上实现时间功能。有没有一种好的方法可以在一个地方实现它,并在任何地方使用它,只需要最少的样板代码?我曾考虑在App.xaml.cs中实现计时器,但我仍然必须以某种方式通知每个viewmodel。我就是想不出一个优雅的解决办法 因为没有代码,所以很难说什么是合适的解决方案,但您可以使用基本ViewModel并从中继承
或者,就像您自己说的,在App.xaml.cs中有一个,您可以通过更新它,或者实现您自己的事件,在每个间隔触发,并从您的ViewModels连接到该事件。这是我的解决方案。它使用.NET标准库而不是PCL。您需要System.Threading.Timer的.NET标准,或者需要使用Xamarin.Forms计时器或第三方实现
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);
}
谢谢你的快速回答。我已经从MvvmHelpers插件继承了BaseViewModel,这也会导致在每个viewmodel上运行计时器。这不会是一个性能问题,但我只是不喜欢有多个计时器的想法。我想避免使用消息中心,因为它不那么直观,也不容易搞乱。我想我会选择App.xaml.cs中基于事件的解决方案。
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);
}
}