這是我的解決方案。它使用.NET標準庫而不是PCL。您需要.NET Standard for System.Threading.Timer,否則您需要使用Xamarin.Forms Timer或第三方實現。
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);
}
在視圖模型
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);
}
}
謝謝您的快速答覆。我已經從MvvmHelpers插件的BaseViewModel繼承,這也會導致在每個視圖模型上運行一個計時器。這不會是一個性能問題,但我只是不喜歡有多個定時器的想法。 我想避免消息中心,因爲它不那麼直觀和容易做混亂。我想我會在App.xaml.cs中使用基於事件的解決方案。 – zuckerthoben