在代码隐藏中更改 TextBox 中的文本时,它不会立即更新 [英] Text in a TextBox does not update instantly when change it in the code-behind

查看:27
本文介绍了在代码隐藏中更改 TextBox 中的文本时,它不会立即更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的简化代码中,我希望文本框在获取结果时说请稍候……".然而它从未出现,而是文本框只显示 functionThatTakesASecondOrTwoToRun()

In the simplified code below, I want the text box to say "Please wait.." while the result is being fetched. However it never appears, instead the textBox only displays the result of functionThatTakesASecondOrTwoToRun()

xml...

<Button Name="readDutButton" Content="Read DUT" Click="readDutButton_Click"/>
<TextBox Name="resultTextBox"/>

背后的代码......

code behind....

    private void readDutButton_Click(object sender, RoutedEventArgs e)
    {
        resultTextBox.Text = "Please wait...";   # this never appears

        result = functionThatTakesASecondOrTwoToRun();

        resultTextBox.Text = result;
    }

推荐答案

工作需要在后台线程中进行,例如

The work needs to happen in a background thread, e.g

resultTextBox.Text = "Please wait...";   // this never appears

Task.Factory.StartNew(() => functionThatTakesASecondOrTwoToRun())
.ContinueWith((t) => resultTextBox.Text = t.Result, 
TaskScheduler.FromCurrentSynchronizationContext());

由于 UI 阻塞了线程,因此 UI 没有进行更改以进行更新.TaskScheduler.FromCurrentSynchronizationContext() 因此 ContinueWith 在 UI 线程上执行并有权访问控件.

The UI is not getting a change to update as the the UI is blocking the thread. TaskScheduler.FromCurrentSynchronizationContext() so the ContinueWith is executed on the UI thread and has access to the controls.

这篇关于在代码隐藏中更改 TextBox 中的文本时,它不会立即更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆