列表与LT;>不在DispatcherTimer中更新

时间:2016-05-16 20:23:24

标签: c# .net wpf visual-studio

我有一个带字符串倒计时的List,我想每秒用DispatcherTimer更新它。

初始化(在Windows加载上运行)

pair_list_dash([X,Y], X-Y).

tasks.Add(new Tasks()
{
    title = "Task 1",
    date = "14:30 17 Martie 2016",
    countdown = "1",
    timer = new TimeSpan(0, 15, 32)
});
tasks.Add(new Tasks()
{
    title = "Task 2",
    date = "14:30 17 Martie 2016",
    countdown = "2",
    timer = new TimeSpan(1, 10, 52)
});
listViewTasks.ItemsSource = tasks;

initCountdown();

DispatcherTimer

 public class Tasks
{
 public string title { get; set; }
 public string date { get; set; }
 public string countdown { get; set; }
 public TimeSpan timer { get; set; }
}

XAML

public void initCountdown()
        {
string item = tasks[0].title;
_time = tasks[0].timer; 
_timer = new DispatcherTimer(new TimeSpan(0, 0, 1), DispatcherPriority.Normal, delegate
{
    tasks[0].countdown = _time.ToString("c"); //this does not update
    if (_time == TimeSpan.Zero) _timer.Stop();
    _time = _time.Add(TimeSpan.FromSeconds(-1));
}, Application.Current.Dispatcher);

_timer.Start();
}

从调度员外部我可以更新它,但是从内部工作不起作用。

没有例外且ui不会更新

我想更新listview以显示我添加的时间跨度倒计时。

2 个答案:

答案 0 :(得分:3)

您必须在Tasks类中实现INotifyPropertyChanged接口,并在倒计时属性更改时调用PropertyChanged事件

答案 1 :(得分:1)

更改Tasks课程以实施INotifyPropertyChanged界面。倒计时的价值正在更新,用户界面只是没有收到有关其新价值的通知。

public class Tasks : INotifyPropertyChanged
{
    private string _title;
    public string title
    {
        get { return _title; }
        set { _title = value; OnPropertyChanged("title"); }
    }

    private string _date;
    public string date
    {
        get { return _date; }
        set { _date = value; OnPropertyChanged("date"); }
    }
    private string _countdown;
    public string countdown
    {
        get { return _countdown; }
        set { _countdown = value; OnPropertyChanged("countdown"); }
    }

    private TimeSpan _timer;
    public TimeSpan timer
    {
        get { return _timer; }
        set { _timer = value; OnPropertyChanged("timer"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propName)
    {
        var e = PropertyChanged;
        if (e != null)
        {
            e.Invoke(this, new PropertyChangedEventArgs(propName));
        }
    }
}