在WPF應用程序,我使用文本框,在其中的ContextMenu被重寫這樣的自定義樣式:文本框自定義文本菜單的風格,多線程錯誤
<Style TargetType="{x:Type TextBox}">
<Setter Property="ContextMenu">
<ContextMenu>
<MenuItem Header="Copy"/>
</ContextMenu>
</Setter>
</Style>
這工作完全直到我會在不同的線程一樣的TextBox運行窗口這樣的:
Thread thread = new Thread(()=>
{
TestWindow wnd = new TestWindow();
wnd.ShowDialog();
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
但是這會導致InvalidOperationException異常「調用線程,因爲不同的線程擁有它不能訪問該對象。」
如何避免此問題?
另一種解決方案是使用事件訂閱器進行右鍵單擊並快速創建ContextMenu。 – 2010-11-01 15:10:13