【问题标题】:appendtext on text box only shown in the end all together in wpf文本框上的附加文本仅在最后显示在 wpf 中
【发布时间】:2012-07-26 23:10:29
【问题描述】:

我的程序中有一个简单的文本框。 其他功能:来自用户 textbox1 的另一个输入和一个按钮。 一旦用户在 textbox1 中输入一个值并按下按钮,我就开始检查并向用户打印消息。我的问题是我没有实时看到这些消息,一次一个。消息立即出现,最后出现。 我没有定义数据绑定,因为我认为既然它是一件简单的事情,我就不需要它,还是我错了? 这是我程序的一小部分,它在按钮单击事件处理程序中。

MainText.AppendText("Starting Refiling...\u2028");
foreach (DocumentData doc in Docs)
{
    try
    {
        wsProxy.RefileDocument(doc);
        MainText.AppendText(String.Format("Refilling doc # {0}.{1}\u2028", doc.DocNum, doc.DocVer));
    }
    catch (Exception exc)
    {
        if (exc.Message.Contains("Document is in use") == true)
            MainText.AppendText(String.Format("There was a problem refilling doc # {0}, it is in use.\u2028",doc.DocNum));
        else
            MainText.AppendText(String.Format("There was a problem refilling doc # {0} : {1}.\u2028", doc.DocNum, exc.Message));
    }
}

【问题讨论】:

    标签: c# wpf textbox


    【解决方案1】:

    您正在 GUI 线程中进行所有循环/打印。基本上,您是在给它展示新项目,而不是给它时间展示它们。创建一个background worker 并让他在您发布的foreach 循环中完成工作。这应该允许 UI 线程在文本更改时更新视图,而不是在最后获得所有更改的更新。我发布的链接包含有关如何使用 backgroundworker 类的示例,但这就是我要做的。

    创建后台工作者:

    private readonly BackgroundWorker worker = new BackgroundWorker();
    

    初始化他:

    public MainWindow()
      {
         InitializeComponent();
    
         worker.DoWork += worker_DoWork;
      }
    

    为他创建一个任务:

    void worker_DoWork( object sender, DoWorkEventArgs e)
    {
       // Set up a string to hold our data so we only need to use the dispatcher in one place
       string toAppend = "";
       foreach (DocumentData doc in Docs)
       {
          toAppend = "";
          try
          {
             wsProxy.RefileDocument(doc);
             toAppend = String.Format("Refilling doc # {0}.{1}\u2028", doc.DocNum, doc.DocVer);  
          }
          catch (Exception exc)
          {
             if (exc.Message.Contains("Document is in use"))
                toAppend = String.Format("There was a problem refilling doc # {0}, it is in use.\u2028",doc.DocNum);
             else
                toAppend = String.Format("There was a problem refilling doc # {0} : {1}.\u2028", doc.DocNum, exc.Message);
          }
    
          // Update the text from the main thread to avoid exceptions
          Dispatcher.Invoke((Action)delegate
          {
             MainText.AppendText(toAppend);
          });
       }
    }
    

    当你得到按钮按下事件时启动他:

    private void Button_Click(object sender, RoutedEventArgs e)
      {
         worker.RunWorkerAsync();
      }
    

    【讨论】:

    • 嗨史蒂夫,就是这样!没想到,但 backgroundworker 解决了我的问题。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 2015-09-07
    • 2010-12-07
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多