TextBox custom ContextMenu in Style, multithreading error
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 "T开发者_StackOverflow中文版he 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.
In your piece of code, you want do modify the UI in a non-UI thread, which is not allowed.
You have to make sure you're on the UI thread when applying UI updates. You can check whether this is required by checking the value of object.InvokeRequired
. If needed, you can invoke the method by calling object.Invoke([delegate])
.
Besides that you can also use the dispatcher, see MSDN and this blog. Happy reading
精彩评论