Search code examples
c#wpftextblock

How do I change a TextBlock Text during Buton Click?


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";

}

Solution

  • 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.