在WPF应用程序中,我使用自定义样式的Textbox,其中ContextMenu被覆盖如下:
<Style TargetType="{x:Type TextBox}">
<Setter Property="ContextMenu">
<ContextMenu>
<MenuItem Header="Copy"/>
</ContextMenu>
</Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)
这完全有效,直到我在不同的线程中使用TextBox运行窗口,如下所示:
Thread thread = new Thread(()=>
{
TestWindow wnd = new TestWindow();
wnd.ShowDialog();
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
Run Code Online (Sandbox Code Playgroud)
但这会导致InvalidOperationException"调用线程无法访问此对象,因为另一个线程拥有它."
如何避免这个问题?