简体   繁体   中英

Rendering date into grid as relative time (“5 seconds ago”) and updating it in real time (WPF)?

I am using WPF, XAML and C# to produce a grid which listens to a source of models which have a date field that I want to display relatively. Currently it is displayed with .ToString() , but my actual question is that how would I implement the relative timing (or the active formatting of it) possible in every second. Is there some preferred way to force re-rendering of the UI, because the data does stay the same all the time (only one column needs to be redrawn once a second and the corresponding formatting method called).

If you are binding to a view model, then you can just raise a property change every second.

   public class MyViewModel : ViewModelBase
   {
       private void OnTimerTick()
       {
           OnPropertyChanged("Date");
       }

       public string Date
       {
           get{ return DateTime.Now().AddSeconds(-5).ToString();
       }
   }

Where ViewModelBase implements INotifyPropertyChanged and you are using a DispatcherTimer to raise the timer tick event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM