列表视图有时不显示我的DataSource.cs中的数据

时间:2013-03-11 21:10:01

标签: c# windows-8 windows-runtime winrt-xaml async-await

我是WinRT开发的新手。我正在尝试将数据从我的数据源绑定到ListView。但是当我使用

时有问题
var file = await ApplicationData.Current.LocalFolder.GetFileAsync("tasks.xml");
var readStream = await FileIO.ReadTextAsync(file);

如果我使用此代码,那么应用程序有时不会在ListView中显示数据(它实际上是随机的,有时它显示一切正常,有时在ListView中不显示任何内容)。

当我从数据源中删除此代码时,就可以正常工作。

我有这个数据源类(DataSource.cs)

public class InboxPageViewModel
{
    public List<Task> Items { get; set; }

    public InboxPageViewModel()
    {
        GetTasks();
    }

    private async void GetTasks()
    {
        try
        {
            var file = await ApplicationData.Current.LocalFolder.GetFileAsync("tasks.xml");
            var readStream = await FileIO.ReadTextAsync(file);

            var tasksList = new List<Task>
            {
                new Task { Name = "a", DueDate = "b", Project = "c", Context = "d"},
            };

            Items = tasksList;
        }
        catch (Exception ex)
        {
            new MessageDialog(ex.Message).ShowAsync();
        }
    }
}

public class Task
{
    public string Name { get; set; }
    public string Category { get; set; }
    public string DueDate { get; set; }
    public string Project { get; set; }
    public string Context { get; set; }
    public string Note { get; set; }
    public string IsFinished { get; set; }
}

1 个答案:

答案 0 :(得分:1)

您永远不应该使用async void方法(除非您正在编写事件处理程序)。

您也不应该从构造函数中调用async方法,有关详细信息,请参阅Stephen Cleary's article about that