【发布时间】:2020-11-04 08:04:45
【问题描述】:
我有这个返回 FlowDocument 的方法。
private static FlowDocument SortFriendsList()
{
FlowDocument DocumentToReturn = new FlowDocument();
Paragraph CurrentParagraph = new Paragraph();
#region Online status ellipse
System.Windows.Shapes.Ellipse OnlineStatus = new System.Windows.Shapes.Ellipse();
OnlineStatus.Height = 30;
OnlineStatus.Width = 30;
OnlineStatus.Stroke = System.Windows.Media.Brushes.Black;
OnlineStatus.StrokeThickness = 1.5;
OnlineStatus.Fill = System.Windows.Media.Brushes.Green;
#endregion
#region Offline status ellipse
System.Windows.Shapes.Ellipse OfflineStatus = new System.Windows.Shapes.Ellipse();
OfflineStatus.Height = 30;
OfflineStatus.Width = 30;
OfflineStatus.Stroke = System.Windows.Media.Brushes.Black;
OfflineStatus.StrokeThickness = 1.5;
OfflineStatus.Fill = System.Windows.Media.Brushes.Red;
#endregion
if (CurrentFriendsList.Count == 0)
{
Label TextToShow = new Label();
TextToShow.FontSize = 16;
TextToShow.Foreground = System.Windows.Media.Brushes.Black;
TextToShow.Content = "Uh oh... It looks like you have no friends for now :(";
CurrentParagraph.Inlines.Add(TextToShow);
CurrentParagraph.Inlines.Add(Environment.NewLine);
DocumentToReturn.Blocks.Add(StatusParagraph);
return DocumentToReturn;
}
else
{
foreach (string Friend in CurrentFriendsList)
{
if (CurrentOnlineUsers.Contains(Friend))
{
CurrentParagraph.Inlines.Add(OnlineStatus);
}
else
{
CurrentParagraph.Inlines.Add(OfflineStatus);
}
#region Text to add after status ellipse
Label TextToShow = new Label();
TextToShow.FontSize = 16;
TextToShow.Foreground = System.Windows.Media.Brushes.Black;
TextToShow.Content = Friend;
#endregion
CurrentParagraph.Inlines.Add(TextToShow);
CurrentParagraph.Inlines.Add(Environment.NewLine);
DocumentToReturn.Blocks.Add(StatusParagraph);
}
return DocumentToReturn;
}
}
我正在调用这样的方法来更新富文本框的文档:
App.Current.Dispatcher.Invoke(() =>
{
try
{
WindowController.MainPage.FriendsListTextBox.Document = SortFriendsList();
}
catch (Exception Exc)
{
Console.WriteLine(Exc.ToString());
}
});
但是。出于某种原因,我得到了
抛出异常:WindowsBase.dll 中的“System.InvalidOperationException” System.InvalidOperationException:调用线程无法访问此对象,因为不同的线程拥有它。
富文本框位于选项卡项中,我尝试使用它的调度程序而不是运气。我也尝试过页面、窗口和富文本框的调度程序,但没有运气。有没有办法找到它的调度员?也许一个方法在尝试执行 dispatcher.checkaccess 时返回 App.Current 中所有调度程序的数组或列表? 在此先感谢:)
【问题讨论】:
-
寻找故障的第一个位置是
WindowController,然后我会避免使用 Page,因为一旦用户导航,它们往往会被破坏,而且它们需要一个 Frame。框架也不继承数据上下文。您的应用中是否有多线程启动? -
你试过
FriendsListTextBox.Dispatcher.BeginInvoke(new Action(() => SortFriendsList()))吗? -
是的,它返回
'System.InvalidOperationException'@mm8 -
@XAMlMAX 我这样做了,但我找不到运行富文本框的威胁,我只是将它移到 UI 线程,它现在可以工作了
标签: c# .net wpf richtextbox dispatcher