这是我的代码,主要的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中不打印任何内容。
我该如何解决?