Reputation: 37
I´d like to change the text of a TextBlock
during a Button_Click
in WPF.
I tried this but it did not work:
private void Button_Click(object sender, RoutedEventArgs e)
{
myTextBlock.Text = "Status: Not ready";
//Do Something
myTextBlock.Text = "Status: Ready";
}
Upvotes: 2
Views: 1721
Reputation: 86
To avoid writing all the processing in the thread i do it :
private async void Button_Click(object sender, RoutedEventArgs e)
{
myTextBlock.Text = "Status: Not ready";
await Task.Run(() =>
{
Thread.Sleep(1000);
}).ConfigureAwait(true);
//Do your processing
Treatment();
myTextBlock.Text = "Status: Ready";
}
Upvotes: 0
Reputation: 169190
You need to replace the comment //Do Something
with some code that actually does something on another thread. If you don't, you will never get the chance to see the "Status: Not ready" message as the Text
property will be set to "Status: Ready" almost immediately after you have clicked the Button
.
Try this:
private async void Button_Click(object sender, RoutedEventArgs e)
{
myTextBlock.Text = "Status: Not ready";
await Task.Delay(3000); //wait asynchronously for 3 seconds..
myTextBlock.Text = "Status: Ready";
}
After you have confirmed that this works as expected you probably want to start a task that does something meaningful as suggested by @Fruchtzwerg. ConfigureAwait(true)
is superfluous here though:
await Task.Run(() =>
{
//Do something
});
Upvotes: 0
Reputation: 11389
Button_Click
is called out of the UI thread. This means executed code will block updating your UI. A simple solution is to use async
and await
and a new thread to run your blocking action. This allows the UI thread to update the UI during the blocking action.
private async void Button_Click(object sender, RoutedEventArgs e)
{
myTextBlock.Text = "Status: Not ready";
await Task.Run(() =>
{
//Your code here
}).ConfigureAwait(true);
myTextBlock.Text = "Status: Ready";
}
Note that you need to add ConfigureAwait(true)
to use the UI thread again to update the text the second time.
Upvotes: 3