【发布时间】:2016-09-02 06:16:12
【问题描述】:
我是 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,但例如下次我运行我的应用程序时, 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;
}
主页:
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>();
}
【问题讨论】:
-
这确实按预期工作。因此,要么您有更多代码,要么您正在做的事情超出您所说的范围,或者您的设备上发生了一些奇怪的事情,导致该文件出现问题......
-
我添加了 BusRoute 类和 MainPage 的代码,大家可以看看。它几乎是完整的代码。
-
下面已经有人回答了你。这也不是编写应用程序的正确方法,您应该使用绑定。虽然可以像上面那样做一些事情,但它在很多方面已经过时,应该避免。
标签: c# xaml text-files