如何在WPF应用程序的RichTextBox中记录时间?

这是我的代码,主要的xaml.cs文件:

//using statements...

namespace WpfAppTestRichTextBox
{
    public partial class MainWindow : Window
    {
        public Paragraph p = new Paragraph();

        public MainWindow()
        {
            InitializeComponent();
            Start();
        }

        // Initialize the richTextBox...
        public void Start()
        {
            Run r = new Run("");
            p.Inlines.Add(r);
            richTextBox.Document.Blocks.Add(p);
        }

        // Button Click and Start a new Thread to record time for each second.
        private void Button_Click(object sender,RoutedEventArgs e)
        {
            System.Threading.Thread th = new System.Threading.Thread(ChangeText);
            th.Start();
        }

        public void ChangeText()
        {
           while(true)
           {
                this.Dispatcher.Invoke(new action(() =>
                {

                    string time = System.DateTime.Now.ToString() + "\n";
                    Run r = new Run(time);
                    p.Inlines.Add(r);

                    System.Threading.Thread.Sleep(1000);

                }));
            }
        }
    }
}

我在段落中添加了新的Run()并期望richTextBox的内容将被刷新,但是它会阻塞while()并在richTextBox中不打印任何内容。

我该如何解决?

a8496558 回答:如何在WPF应用程序的RichTextBox中记录时间?

问题是您在调度程序线程中处于睡眠状态。您是否打算在调度程序调用之后将其放置?

while(true)
{
    this.Dispatcher.Invoke(new Action(() =>
    {
        string time = System.DateTime.Now.ToString() + "\n";
        Run r = new Run(time);
        p.Inlines.Add(r);
    }));
    System.Threading.Thread.Sleep(1000);
}

Thread.Sleep

  

将当前线程挂起指定的时间。

Dispatcher.Invoke在块内调度代码以在UI线程上运行。将睡眠放在那儿会挂起UI线程,从而导致其冻结。

更新:更好的解决方案是使用调度程序计时器。

public partial class MainWindow : Window
{
    private DispatcherTimer _timer = new DispatcherTimer();
    public Paragraph p = new Paragraph();

    public MainWindow()
    {
        InitializeComponent();
        _timer.Interval = new TimeSpan(0,1);
        _timer.Tick += _timer_Tick;
    }


    private void _timer_Tick(object sender,EventArgs e)
    {
        string time = System.DateTime.Now.ToString() + "\n";
        Run r = new Run(time);
        p.Inlines.Add(r);
    }

    private void Button_Click(object sender,RoutedEventArgs e)
    {
        Run r = new Run("");
        p.Inlines.Add(r);
        richTextBox.Document.Blocks.Add(p);
        _timer.Start();
    }
}
,

首先,将您的方法更改为异步是一个好主意,但是要回答您的问题,由于该方法永不结束或将控制权交还给调用者,您的UI可能没有刷新。尝试强制刷新:

 if (richTextBox.InvokeRequired)
 {
      richTextBox.Invoke(new MethodInvoker(delegate
      {
          richTextBox.Refresh();

       }));
 }
 else richTextBox.Refresh();
 Application.DoEvents();

如果这行不通,请尝试执行某些操作,例如在调试模式下运行并在某些时候检查p的值,或者尝试更改文本框的值。直接输入文本以查看实际错误在哪里

本文链接:https://www.f2er.com/3155324.html

大家都在问