Background STA thread with custom window style using window chrome throwing cross threaded access exception

南楼画角 提交于 2019-12-02 07:39:05

The root of the problem is when you do this:

<Setter Property="WindowChrome.WindowChrome">
    <Setter.Value>
        <WindowChrome CaptionHeight="44"
                      GlassFrameThickness="-1"
                      CornerRadius="0,0,0,0" />
    </Setter.Value>
</Setter>

The value (WindowChrome instance in this case) is created once and preserved in style when it is constructed. It will not create new instances each time style is applied to control. First you apply style to main window. At this point style is created from xaml, and so WindowChrome instance is created. When you apply style to background window from another thread - style is not recreated, already created instance of Style is used. It is being noticed that style setter contains value created in another thread, that value is freezable but not frozen - so it fails with exception, because it is considered dangerous (and will not work anyway because you cannot assign this WindowChrome instance created in another thread to your BackgroundWindow, nor can you clone it).

When you apply x:Shared=False to style - new instance of Style is created on each request, avoiding the problem (because new instance of WindowChrome is created too for each instance of Style). Another way to force new intsance is:

<WindowChrome x:Key="chrome" x:Shared="False"
              CaptionHeight="44"
              GlassFrameThickness="-1"
              CornerRadius="0,0,0,0" />

<Style ...>
    <Setter Property="WindowChrome.WindowChrome" Value="{DynamicResource chrome}"/>
</Style>

Only use multiple UI threads when there is really no other way, because they might be tricky.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!