我在一些非GUI线程上创建了一个SolidColorBrush
,并且想将它传递给一个GUI线程来显示它,但是我得到了InvalidOperationException
:The calling thread cannot access this object because a different thread owns it.
(即使我尝试了Freeze();
它)。我如何传递是在线程X创建线程ÿ对象?如何传递是在线程X中创建一个WPF对象,线程Y'
我知道我可以在GUI线程中使用Dispatcher
创建此SolidColorBrush
对象,但这会使所有事情变得复杂......我想在工作线程中创建它。
的附加细节:
我初始化一些静态代表在一些静态类,以允许将来自业务层消息到GUI:
public static class Gui{
private static PrintMethodDelegate _printMethod;
public static void InitializeGuiInterface(PrintMethodDelegate printMethod){
_printMethod = printMethod;
}
public static void Print(GuiMessage data) { _printMethod(data); }
}
初始化(在GUI线程):
Gui.InitializeGuiInterface(_messagesToUserHandler.PrintMessage);
然后在另一个(non-gui)线程中,我使用它:
Gui.Print(new GuiMessage(testDescription) { Foreground = new SolidColorBrush(someColor) });
而GuiMessage
是:
public class GuiMessage {
public string Msg { get; set; }
private SolidColorBrush _foregroundBrush;
public SolidColorBrush Foreground
{
get { return _foregroundBrush; }
set { _foregroundBrush = value; }
}
}
您是否尝试将错误消息写入Google?它返回我们可能给出的所有答案。 – I4V 2013-05-06 06:55:23
我想简短的答案是你不能。应该在UI线程上创建和处理所有与GUI相关的控件/工件。 – 2013-05-06 06:59:48
@ I4V:是的,我试过了。谢谢你的建议。 – Tar 2013-05-06 07:11:39