WPF not updating textbox while in progress

痞子三分冷 提交于 2019-11-28 00:26:39

Just do this.

private void button1_Click(object sender, RoutedEventArgs e)
    {
        ThreadPool.QueueUserWorkItem((o) =>
             {
                 Dispatcher.Invoke((Action) (() => info.Text = "step 1"));
                 wait(1000);
                 Dispatcher.Invoke((Action) (() => info.Text = "step 2"));
                 wait(1000);
                 Dispatcher.Invoke((Action) (() => info.Text = "step 3"));
                 wait(1000);
                 Dispatcher.Invoke((Action) (() => info.Text = "step 4"));
                 wait(1000);
             });
    }

The GuI Thread won't refresh until the button1_Click method returns. That's why you only see the last value. You have to put long methods into asynchronous calls or use threads.

The measure/arrange (and therefore the render) happens asynchronously so if you want to force the screen to update then you would need to call UpdateLayout.

What if you tried a DispatcherFrame to simulate what forms DoEvents would accomplish:

You may need to include System.Security.Permissions and System.Windows.Threading. After that pplace a call to DoEvents() after each of your sleeps and you get the desired result.

[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public void DoEvents()
{
    DispatcherFrame frame = new DispatcherFrame();
    Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
        new DispatcherOperationCallback(ExitFrame), frame);
    Dispatcher.PushFrame(frame);
}

public object ExitFrame(object f)
{
    ((DispatcherFrame)f).Continue = false;

    return null;
}

Link to MSDN article: http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.pushframe.aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!