简体   繁体   中英

How to add timer to binding wpf uwp c#

How to add a timer for all binding objects? I have a list of Bikes, which contains two propertys (I get propertys from JSON) :

  using myApi;

  public sealed partial class BikesSample: Page
    {
     List<Bike> Bikes = new List<Bike>();

    public BikesSample()
    {
      this.InitializeComponent();
      //get JSON
      dynamic getList = myApi.Api.getList();
      Newtonsoft.Json.Linq.JArray y = getList.list;

      for (int x = 0; x < y.Count; x++)
      {
       //converting time
       double doubleTime =      Convert.ToDouble((getList.list[x].endtime).ToString());
       TimeSpan ResTime = TimeSpan.FromSeconds(doubleTime);

       Bikes.Add(new Bike()
                    { number = (getList.list[x].number).ToString(),
                        endtime = ResTime.ToString()});

                    BikesList.ItemsSource = Bikes;
      }
    }
 }
 public class reserveBike
 {
  public string number { get; set; }
  public string endtime { get; set; }
 }

And xaml like:

<ListView x:Name="BikesList" Margin="0,60,-360,-630">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid Width="360" VerticalAlignment="Center">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>

                        <TextBlock Grid.Column="0" Text="{Binding number}"/>

                        <TextBlock Grid.Column="1" Text="{Binding endtime}"/> //Here should be a timer mm:ss

                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

I need to make all "endtime" propertys at ListView as timers. I have trying to use DispatcherTimer, but I don't understand where and how I should to use DispatcherTimer.Tick method. Endtime property I get in seconds.

I have used MVVM concept. Implement INotifyPropertyChanged for Bike,since it has to update ui for each seconds;

    public class Bike:INotifyPropertyChanged
        {
            public string number { get; set; }
            public string endtime { get; set; }
            string _foramtedtime;
            public string FormattedEndTime
            {
                get
                {
                    return _foramtedtime;
                }
                set
                {

                    if(value!=_foramtedtime)
                    {
                        _foramtedtime = value;
                        OnPropertyChanged("FormattedEndTime");
                    }
                }
                }

            void OnPropertyChanged(string propertyName)
            {
                // the new Null-conditional Operators are thread-safe:
                this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }


            public TimeSpan EndTimeinTimeSpan;

            public event PropertyChangedEventHandler PropertyChanged;

            public Bike(string numb,string endtim)
            {
                number = numb;
                endtime = endtim;
                var seconds = int.Parse(endtime);
                FormattedEndTime=  string.Format("{0:00}:{1:00}",(seconds / 60) % 60, seconds % 60);
                EndTimeinTimeSpan = TimeSpan.Parse(string.Format("{0:00}:{1:00}:{2:00}", seconds / 3600, (seconds / 60) % 60, seconds % 60));
            }
        }
    public sealed partial class MainPage : Page
        {
               VM = new TestViewModel();
            DataContext = VM;
            this.Loaded += MainPage_Loaded;
                DispatcherTimer timertostoop;
                DispatcherTimer timer;
               public MainPage()
               {
                       TimeSpan time =( DataContext as TestViewModel).Bikes.Max(x => x.EndTimeinTimeSpan);
                timertostoop   = new DispatcherTimer() { Interval = time };
                timertostoop.Tick += Timertostoop_Tick;
                timer = new DispatcherTimer() { Interval =TimeSpan.FromSeconds(1) };
                timer.Tick += Timer_Tick;
               }
                 private void Timertostoop_Tick(object sender, object e)
            {
                if (timer != null && timer.IsEnabled)
                    timer.Stop();
                timertostoop.Stop();
            }

            private async void MainPage_Loaded(object sender, RoutedEventArgs e)
            {

                timer.Start();

            }
            private void Timer_Tick(object sender, object e)
            {
       if(!timertostoop.IsEnabled)
            timertostoop.Start();
              foreach(var bike in VM.Bikes)
                {
                    if(bike.EndTimeinTimeSpan>TimeSpan.FromSeconds(0))
                    {
                        bike.EndTimeinTimeSpan = bike.EndTimeinTimeSpan - TimeSpan.FromSeconds(1);
                        bike.FormattedEndTime = string.Format("{0:00}:{1:00}", Math.Floor((bike.EndTimeinTimeSpan.TotalSeconds/ 60) ), bike.EndTimeinTimeSpan.Seconds);
                    }
                }
            }

        }
  <ListView x:Name="BikesList" ItemsSource="{Binding Bikes}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid Width="360" VerticalAlignment="Center">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>

                        <TextBlock Grid.Column="0" Text="{Binding number}"/>

                        <TextBlock Grid.Column="1" Text="{Binding FormattedEndTime}"/> 

                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

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