In WPF application I use Textbox with custom style in which ContextMenu is overriden like this:
<Style TargetType="{x:Type TextBox}">
<Setter Property="ContextMenu">
<ContextMenu>
<MenuItem Header="Copy"/>
</ContextMenu>
</Setter>
</Style>
This works perfectly until I'll run window with TextBox in different threads like this:
Thread thread = new Thread(()=>
{
TestWindow wnd = new TestWindow();
wnd.ShowDialog();
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
But this causes InvalidOperationException "The calling thread cannot access this object because a different thread owns it.".
How to avoid this problem?
The problem is that your style is reused as optimization, so the ContextMenu is reused - this is standard and works well for single threaded, but not for multithread.
I would try moving the style to the resourcedictionary and referencing it as a StaticResource, I would then mark with: x:Shared="false" This will create a new instance everytime the resource is accessed - I am not sure it works for the "catch all" key less style you have. Then you could make the contextmenu a resource and refere it as a StaticResource - that should do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With