更新ListView内的倒计时

时间:2016-03-12 21:46:20

标签: c# listview mvvm win-universal-app

我想对ListView中的每个项目进行倒计时,但它不会更新。我尝试在调度程序计时器引发的tick事件中调用该属性,但这不会起作用。有关如何实现这一目标的任何建议吗?

public ObservableCollection<TimeAndName> items { get; set; }
    DispatcherTimer timer = new DispatcherTimer(); 
    public MyViewModel()
    {        
                LoadItems();
                TimeMethod();                   
    }
    public void TimeMethod()
    {
        timer.Interval = new TimeSpan(0, 0, 0, 0, 0);
        timer.Tick += myTimer_tick;        
        timer.Start();
    }
    public void LoadItems()
    {
        items = new ObservableCollection<TimeAndName>();
        items.Add(new TimeAndName("first item", new TimeSpan(0, 0, 1, 0), ""));            
    }
    private void myTimer_tick(object sender, object e)
    {
        foreach (var timeAndName in items)
        {
            var now = DateTime.Parse(DateTime.Now.ToString("T"));
            var deadline = DateTime.Parse(timeAndName.Deadline.ToString());
            TimeSpan dif = now - deadline;
            timeAndName.TimeString = dif.ToString();
        }             
    }
    #region NotifyRegion
    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    } 
    #endregion

XAML:

<Grid Background="#FF22313F">
  <Grid.DataContext>
     <local:MyViewModel/>
  </Grid.DataContext>
  <ListView x:Name="listView" ItemsSource="{Binding items, Mode=TwoWay,         UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Height="360" Margin="1047,196,0,0" VerticalAlignment="Top" Width="467" Background="#FF574C89"/>
</Grid>

1 个答案:

答案 0 :(得分:1)

似乎您只绑定了项目集合,而没有定义合适的 ItemTemplate 。示例可能如下所示:

<ListView x:Name="listView" ItemsSource="{Binding items, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Height="360" Margin="1047,196,0,0" VerticalAlignment="Top" Width="467" Background="#FF574C89">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding TimeString}"/>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

就目前而言,你已经绑定了ObservableCollection,只有在添加/删除项目时才更新 ListView - 未修改 - 如果你声明 ItemTemplate with binding和 INotifyPropertyChanged ,它会起作用。