c# - List<> 不在 DispatcherTimer 中更新

标签 c# .net wpf visual-studio

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

Init(在 windows 负载下运行)

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();

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

调度器定时器

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();
}

XAML

<ListView Margin="0,30,0,0" Name="listViewTasks">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="1*"/>
                    <ColumnDefinition Width="1*"/>
                </Grid.ColumnDefinitions>
                <StackPanel HorizontalAlignment="Left" Margin="0,0,50,0">
                    <TextBlock Text="{Binding title}" Cursor="Hand"/>
                    <TextBlock Text="{Binding date}" />
                </StackPanel>
                <StackPanel HorizontalAlignment="Right" Grid.Column="1">
                    <TextBlock  Text="{Binding countdown}" />
                </StackPanel> 
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

我可以从调度程序外部更新它,但从内部无法正常工作。

没有异常,ui 没有更新

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

最佳答案

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

关于c# - List<> 不在 DispatcherTimer 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37262637/

相关文章:

c# - CloudQueueMessage 没有 byte[] ctor,有什么解释吗?

c# - CommandType为StoredProcedure时如何使用IDbCommandInterceptor修改SQL

.net - 寻找一个 FOSS 工具来显示 .NET 程序集链接依赖项

.net - 从 Dapper ORM 调用 Oracle 存储过程时,无法将类型 'System.Int32[]' 的对象转换为类型“System.IConvertible”

c# - 如何从 wpf 文本框中的十进制数字中删除无效条目

WPF TextBlock 负数为红色

c# - 使用 jQuery Ajax 将对象列表传递给 ActionResult MVC Controller 方法

c# - 是否可以使用 c# 类创建此 JSON 格式?

.net - 如何打印StackOverflowException的堆栈跟踪

wpf - 如何在 WPF 控件中运行 Google Earth