他の質問に従って、ディスパッチャーを使用してワーカースレッドからWPFテキストブロックにコンテンツを追加しようとしました。私は次の方法を使用しています:
private void AppendLineToChatBox(Inline message)
{
chatBox.Dispatcher.BeginInvoke(new Action(() =>
{
chatBox.Inlines.Add(message);
chatBox.Inlines.Add("\n");
scroller.ScrollToBottom();
}));
}
XAMLの場合:
<Grid Height="200" Width="300" HorizontalAlignment="Left">
<ScrollViewer Name ="scroller">
<TextBlock TextWrapping="Wrap" Background="White" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Name="chatBox" />
</ScrollViewer>
</Grid>
バックグラウンドスレッドからAppendLineToChatBox()を呼び出すと、まだ次の例外が発生します。
System.InvalidOperationExceptionは未処理でしたHResult=-2146233079
メッセージ=別のスレッドがオブジェクトを所有しているため、呼び出し元のスレッドはこのオブジェクトにアクセスできません。
正しい方法をいただければ幸いです。