i'm beginner c# , xaml.
in app read lines of text list this:
string path = "ms-appx:///" + _index + ".txt"; storagefile samplefile = await storagefile.getfilefromapplicationuriasync(new uri(path)); _stopslist = await fileio.readlinesasync(samplefile, windows.storage.streams.unicodeencoding.utf8);
and put combobox2:
combobox2.itemssource = routeslist[combobox.selectedindex]._stopslist;
one time run app in debug mode, combobox2 correctly filled lines file (like 1, example next time when run app, combobox2 empty (2) , next _stopslist appears count: 0. content in combobox2 doesn't appear every time.
busroute class:
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 { { 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>(); }
so problem here getstopslist()
marked run async
. when call getstopslist
in busroute
constructor, code continues immediately, , reaches this.combobox2.itemssource = routeslist[combobox.selectedindex]._stopslist;
@ point readlinesasync
hasn't completed yet (execution in constructor wasn't paused), empty list of data bound combobox2
.
the reason works when debugging when add break point , inspect code causing artificial delay allows enough time readlinesasync
complete.
try changing public async void getstopslist()
public async task getstopslist()
allow caller await
function. need call await getstopslist();
before binding data list.
you can't await
inside constructor, need call intialisation function somewhere else. posses interesting challenge code inside constructor. perhaps there page
event can in, e.g. on load
or on init
.
Comments
Post a Comment