【问题标题】:Is there a WPF Output Monitor Control like the Visual Studio Debug Output是否有像 Visual Studio 调试输出这样的 WPF 输出监视器控件
【发布时间】:2012-12-05 17:13:14
【问题描述】:

我正在尝试将输出监视器添加到我的 WPF 应用程序。 类似于 Visual Studio 中的调试输出的只读监视器。

是否有一个 WPF 控件已经提供了我需要的功能? 或者有没有办法可以重用 Visual Studio 中的控件?

目前我正在使用由 StringBuilder 支持的标准文本框。更新转到 StringBuilder,而 TextBox 每 200 毫秒获取最新的字符串。

我的问题是,随着输出字符串变长,这会变得非常慢。

【问题讨论】:

    标签: c# wpf visual-studio wpf-controls


    【解决方案1】:

    我会使用 RichTextBox 控件来输出数据。

    在这个示例中,我的性能完全没有问题。

    public partial class MainWindow : Window
    {
        private int counter = 0;
        public MainWindow()
        {
            InitializeComponent();
            Loaded+=OnLoaded;
        }
    
        private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
        {
    
            for (int i = 0; i < 200; i++)
            {
                AddLine(counter++ + ": Initial data");
            }
    
            var timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 0, 0, 200);
            timer.Tick += TimerOnTick;
            timer.IsEnabled = true;
        }
    
        private void TimerOnTick(object sender, EventArgs eventArgs)
        {
            AddLine(counter++ + ": Random text");
        }
    
        public void AddLine(string text)
        {
            outputBox.AppendText(text);
            outputBox.AppendText("\u2028"); // Linebreak, not paragraph break
            outputBox.ScrollToEnd();
        }
    }
    

    还有 XAML

    <Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <RichTextBox x:Name="outputBox"
                         VerticalScrollBarVisibility="Visible" 
                         HorizontalScrollBarVisibility="Visible" 
                         IsReadOnly="True">
                <FlowDocument/>
            </RichTextBox>
    
        </Grid>
    </Window>
    

    而且扩展它可能很容易。如果滚动位置不在末尾,请不要滚动到末尾,例如,这样您就可以在文本框仍在更新时查看旧数据。

    【讨论】:

    • 我正在使用 MVVM 模式和 DataBinding,因此获取数据的 ViewModel 无法直接调用 RichTextBox 的 AppendText 方法。但我会尝试解决这个问题。也许我可以使用 DependencyProperty。
    • Hm.. 在 ViewModel 中创建一个 View 监听的事件,然后从那里调用 AddLine() 怎么样?如果没有,您可以尝试绑定到文档,但我不确定以这种方式添加一行文本的最佳方法是什么。 (注意,绑定到 Document 很困难)
    • 我使用 RichTextBox 方法并实现了我自己的写入器,该写入器写入 FlowDocument。性能相当不错。抱歉让您久等了。我度假了很长一段时间。
    • 由于性能问题,我最终放弃了这个解决方案,并且更难扩展,然后这个解决方案暗示了这一点。我在尝试进行大量行追加时遇到了性能问题(顺便说一句,我不得不使用新行分隔,以便能够将输出复制到记事本),并且如果光标不在最后一个上,我也尝试不自动滚动线。确定 ritchtextbox 上的行号真的很复杂。最后使用了一个简单的文本框(也有附加行)和一个启用/禁用自动滚动的复选框。
    • 嗨@Akselk 感谢您的代码。有一个问题,当我从输出中复制文本时,换行符没有被复制,因此难以阅读。如果我将 "\u2028" 替换为 \n 它工作正常,但输出显示为两行而不是一行。
    猜你喜欢
    • 1970-01-01
    • 2023-01-03
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多