WPF not updating textbox while in progress

隐身守侯 提交于 2019-12-17 16:40:49

问题


I have this code:

void wait(int ms)
{
    System.Threading.Thread.Sleep(ms);
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    info.Text = "step 1";
    wait(1000);
    info.Text = "step 2";
    wait(1000);
    info.Text = "step 3";
    wait(1000);
    info.Text = "step 4";
    wait(1000);
}

And problem is that textbox.text is updated after whole void button1_Click finished. It is not updated ON AIR :(

Please, How to do that?


回答1:


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);
             });
    }



回答2:


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.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/4205502/wpf-not-updating-textbox-while-in-progress

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