apero
apero

Reputation: 1154

How can I asynchronous databind data to my textblock using XAML

I have trouble with binding asynchronous data to a textblock.

When I go through my code step by step using F11 it works. But when I just run my app it throws a fault saying:

Value cannot be null. 

It looks like the code runs too fast.

Here's my code:

settings.GetSettings();
tbNamePlayer1.Text = settings.player1;
tbNamePlayer2.Text = settings.player2;

GetSettings method:

StorageFolder sf = await Package.Current.InstalledLocation.GetFolderAsync("XML");
StorageFile st;
try {
    st = await sf.GetFileAsync(filename);
} catch {
    WriteInitialSettings();
}
st = await sf.GetFileAsync(filename);
var reader = XmlReader.Create(st.Path);
XmlSerializer ser = new XmlSerializer(typeof(Settings));
settings = (Settings)ser.Deserialize(reader);
player1 = settings.player1;
player2 = settings.player2;
difficulty = settings.difficulty;
win = settings.win;
lose = settings.lose;

Upvotes: 1

Views: 606

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 456437

You need to await your GetSettings method:

await settings.GetSettings();
tbNamePlayer1.Text = settings.player1;
tbNamePlayer2.Text = settings.player2;

That way your method will (asynchronously) wait until GetSettings is complete before assigning the properties.

Upvotes: 1

blindmeis
blindmeis

Reputation: 22435

look at IsAsync or/and Priority Binding in xaml. maybe this can help you out

http://www.switchonthecode.com/tutorials/wpf-tutorial-priority-bindings

Upvotes: 0

Related Questions