【发布时间】:2013-03-15 08:16:55
【问题描述】:
我已尝试按照其他问题通过使用 Dispatcher 从工作线程向 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
Message=调用线程无法访问该对象,因为 不同的线程拥有它。
正确的方法将不胜感激。
【问题讨论】:
-
现在在哪一行得到异常?你确定不是
scroller.ScrollToBottom()? -
chatBox.Inlines.Add(message) 抛出异常
-
我不认为这是一个重复的问题,因为我已经在使用调度程序了。