如何在按钮单击WPF上运行循环时写入文本框 [英] How write to a text box while loop running on button click WPF

查看:95
本文介绍了如何在按钮单击WPF上运行循环时写入文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我单击按钮时,代码正确运行,但在整个while循环结束之前,文本框不会在UI中更新。我需要它来更新每个循环的文本框。



When I click on the button the code runs correctly but the text box does not update in the UI until the entire while loop has finished. I need it to update the text box on every loop.

private void btnBeginTransfer_Click(object sender, RoutedEventArgs e)
       {

           serial.PortName = port;
           serial.BaudRate = baud;
           serial.DataBits = dataBit;
           serial.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopBit);
           serial.Handshake = (Handshake)Enum.Parse(typeof(Handshake), handshake);
           serial.Parity = (Parity)Enum.Parse(typeof(Parity), parity);
           serial.ReadTimeout = rTimeout;
           serial.WriteTimeout = wTimeout;
           serial.Open();

           //reading file and writing it across
           using (System.IO.TextReader reader = System.IO.File.OpenText(txtSelect.Text))
           {
               string line;

               while ((line = reader.ReadLine()) != null)
               {
                   serial.WriteLine(line);
                   //updating the text box
                   txtTransferredData.Text += line + "\n";

               }
           }

           serial.Close();

       }





示例代码非常有用。



Sample code would be very helpful.

推荐答案





您可以使用后台工作程序,这样您的UI就不会停止,直到您的while循环运行。让我知道它是否适合你。



参考:后台工作者 [ ^ ]



谢谢
Hi,

You can use background worker so your UI wont be stop till the time your while loop is running. Let me know if it wont work for you.

Refer : Background Worker[^]

Thanks


你需要在文本框上应用了刷新,这样它就会在循环运行时显示所有文本。



你需要有一个包含你的ExtensionMethods的静态类刷新例程。



You will required to have the Refresh applied on your textbox so it will display all the texts while the loop is running.

You will require to have a static class for ExtensionMethods that will contain your refresh routine.

public static class ExtensionMethods
    {
        private static Action EmptyDelegate = delegate() { };

        public static void Refresh(this UIElement uiElement)
        {
            uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
        }
    }







现在只需拨打




now simply calling

txtTransferredData.Refresh()

也会在循环内刷新文本框文本。

我认为这适用于你的情况。

will refresh your textbox text within loop as well.
I think this will work in your case.


这篇关于如何在按钮单击WPF上运行循环时写入文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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