每次都不会从文件中读取行

时间:2016-09-01 20:48:40

标签: c# xaml text-files

我是C#和XAML的初学者。

在我的应用程序中,我阅读了如下列出的文本行:

string path = "ms-appx:///" + _index + ".txt";
StorageFile sampleFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(path));
_stopsList = await FileIO.ReadLinesAsync(sampleFile, Windows.Storage.Streams.UnicodeEncoding.Utf8);

我把它放到 combobox2

comboBox2.ItemsSource = routesList[comboBox.SelectedIndex]._stopsList;

有一次我在调试模式下运行我的应用程序, combobox2 正确填充了文件中的行(例如1,但是例如下次运行我的应用时,< em> combobox2 为空(2), _stopsList 旁边出现 Count:0 combobox2 中的内容没有&每次都会出现。

BusRoute课程:

class BusRoute
{
    public BusRoute(string name, int index)
    {
        Name = name;
        _index = index;
        GetStopsList();
    }

    public async void GetStopsList()
    {
        string path = "ms-appx:///" + _index + ".txt";
        StorageFile sampleFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(path));
        _stopsList = await FileIO.ReadLinesAsync(sampleFile, Windows.Storage.Streams.UnicodeEncoding.Utf8);
    }

    public string Name
    {
        get { return _routeName; }
        set
        {
            if (value != null)
            {
                _routeName = value;
            }
        }
    }

    public IList<string> _stopsList = new List<string>();
    private string _routeName;
    private int _index;
}

的MainPage:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.DataContext = this;
        this.InitializeComponent();

        routesList.Add(new BusRoute("Laszki – Wysocko - Jarosław", 1));
        routesList.Add(new BusRoute("Tuchla - Bobrówka - Jarosław", 2));

        this.comboBox.ItemsSource = routesList;
        this.comboBox.DisplayMemberPath = "Name";
        this.comboBox.SelectedIndex = 0;

        this.comboBox2.ItemsSource = routesList[comboBox.SelectedIndex]._stopsList;
    }

    List<BusRoute> routesList = new List<BusRoute>();
}

1 个答案:

答案 0 :(得分:1)

所以问题在于GetStopsList()被标记为运行async。当您在GetStopsList构造函数中调用BusRoute时,代码会立即继续,并最终到达this.comboBox2.ItemsSource = routesList[comboBox.SelectedIndex]._stopsList;此时ReadLinesAsync尚未完成(在构造函数没有暂停),因此一个空的数据列表绑定到comboBox2

调试时这样做的原因是,当您添加断点并检查代码时,会导致人为延迟,从而有足够的时间让ReadLinesAsync完成。

尝试将public async void GetStopsList()更改为public async Task GetStopsList()这将允许来电者await这个功能。然后,您需要在绑定数据列表之前调用await GetStopsList();

你不能在构造函数中await,所以你需要从其他地方调用初始化函数。这具有一个有趣的挑战,因为所有代码都在构造函数中。也许您可以执行Page事件,例如在LoadInit上。