System.ComponentMode.BackgroundWorkerのDoWorkから「FlowDocument」WPFオブジェクトを作成しましたが、WPF UIスレッドでWPFオブジェクトにアクセスできません。BackgroundWorkerとWPF
using System;
using System.Windows;
using System.Windows.Documents;
using System.ComponentModel;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
BackgroundWorker bw = new BackgroundWorker();
public MainWindow()
{
InitializeComponent();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted+=new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
FlowDocument myFlowDocument = new FlowDocument();
Paragraph myParagraph = new Paragraph();
myParagraph.Inlines.Add(new Bold(new Run("Some bold text in the paragraph.")));
myFlowDocument.Blocks.Add(myParagraph);
e.Result = myFlowDocument;
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//runtime error occured here.
fviewer.Document = (FlowDocument)e.Result;
}
}
}
私は別のスレッドでWPFオブジェクトにアクセスすると聞いて、私はディスパッチャ()を使用する必要があります。 しかし、RunWorkerCompleted()はUIの別のスレッドではないので、私は混乱しています。 myFlowDocumentにはどのようにアクセスできますか?
しかし、fviewerとフロードキュメントは別々のスレッドで作成されているため、それらを組み合わせることはできません。 –
コードが機能しませんでした。同じ例外が発生しました。ありがとう。 – mjk6026
@Bob - 確かに。ナイスキャッチ。私は私の答えを更新しました。 – vcsjones