如何在 WPF 中有效地将文本流式传输到屏幕?

Mat*_*hew 3 wpf

我想流式传输一堆文本以显示长时间运行的任务(例如 Visual Studio 中的输出窗口)的状态/进度。

目前我有这样的XAML:

    <ScrollViewer Canvas.Left="12" Canvas.Top="12" Height="129" Name="scrollViewer1" Width="678">
        <TextBlock Name="text"  TextWrapping="Wrap"></TextBlock>
    </ScrollViewer>
Run Code Online (Sandbox Code Playgroud)

后面的代码:

    private void Update(string content)
    {
        text.Text += content + "\n";
        scrollViewer1.ScrollToBottom();
    }
Run Code Online (Sandbox Code Playgroud)

一段时间后,它变得非常慢。
有没有推荐的方法来做这种事情?我是否使用了正确类型的控件?

谢谢!

Ken*_*art 5

至少,您需要使用 readonlyTextBox并使用该AppendText()方法来附加文本。

当然,如果您有足够的文本量,您仍然无法避免性能问题。在这种情况下,您可能需要研究虚拟化(数据和 UI)解决方案。

  • 我对 TextBox 优于 TextBlock 的选择感到惊讶。想测试他们的表现,测试完全反映了你的观点,肯特。将 100K 字添加到 TextBlock 需要 91625 毫秒,而对于 TextBox,它仅需要 10737 毫秒。 (4认同)