2017-07-03 21 views
0

我有一個Xamarin.Forms應用程序,其頁面全部使用ControlTemplate實現自定義標題。在標題中,一些頁面(因此ControlTemplates)有一個時間標籤,在ViewModel中使用定時器(使用綁定)進行更新。在多個Xamarin.Forms視圖中顯示時間

我目前正在做的是在每個ViewModel上實現時間功能。有沒有一種很好的方法在一個地方實現這一點,並使用最少的樣板代碼在任何需要的地方使用它?我想過在App.xaml.cs中實現定時器,但我仍然必須以某種方式通知每個視圖模型。我只是不能想出一個優雅的解決方案。

回答

0

這是我的解決方案。它使用.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); 
    } 
} 
0

因爲沒有代碼,所以很難說什麼是合適的解決方案,但是您可以使用基本ViewModel並從中繼承?或者像你自己說的那樣,在你的App.xaml.cs中有一個,你可以通過Messaging Center來更新它,或者實現你自己的事件,它在每個時間間隔觸發,並從你的ViewModel中鉤住。

+0

謝謝您的快速答覆。我已經從MvvmHelpers插件的BaseViewModel繼承,這也會導致在每個視圖模型上運行一個計時器。這不會是一個性能問題,但我只是不喜歡有多個定時器的想法。 我想避免消息中心,因爲它不那麼直觀和容易做混亂。我想我會在App.xaml.cs中使用基於事件的解決方案。 – zuckerthoben

相關問題