次线程不能直接修改主线程UI的界面,需要使用以下方法
this.Dispatcher.Invoke(DispatcherPriority.Normal,
new Action(() =>
{
//调用主线程UI的的代码
}));
如:
void LoadFile() { try { if (string.IsNullOrEmpty(filename)) { //加载建设中 return; } if (!File.Exists(filename)) { //加载建设中 return; } this.Dispatcher.BeginInvoke(new Action(() => { using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read)) { string ext = System.IO.Path.GetExtension(filename); System.Windows.Documents.FlowDocument flowDocument = new System.Windows.Documents.FlowDocument(); flowDocument.IsOptimalParagraphEnabled = true; flowDocument.FlowDirection = System.Windows.FlowDirection.LeftToRight; flowDocument.IsHyphenationEnabled = true; switch (ext) { case ".rtf": TextRange range = new TextRange( flowDocument.ContentStart, flowDocument.ContentEnd); range.Load(fs, DataFormats.Rtf); break; default: break; } flowDocument.ColumnWidth = 540; FlowDocPageView1.Document = flowDocument; } }), DispatcherPriority.Normal); } catch { return; } }