Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 "The calling thread cannot access this object because a different thread owns it.".

How to avoid this problem?

like image 947
Rikker Serg Avatar asked Oct 29 '10 05:10

Rikker Serg


1 Answers

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.

like image 82
Rune Andersen Avatar answered Sep 23 '22 11:09

Rune Andersen