Static resource shared in merged dictionaries

前端 未结 2 958
孤街浪徒
孤街浪徒 2021-01-04 18:00

I\'m currently working on having dictionaries of styles and templates that I can dynamically apply to my application. Before this \"new wanted\" dynamical behavior, I had se

相关标签:
2条回答
  • 2021-01-04 18:47

    Great answer by John explaining why this is happening. So the problem is that when using merged dictionaries within a merged dictionary, the inner dictionaries can't "use" each other as StaticResource.

    Basic solutions:

    • Use DynamicResource
    • Use just a single level of hierarchy from App.xaml when using StaticResource

    Both of these solutions have problems. DynamicResource has a performance problem. The 2nd solution limits you on how you organize your XAML resources.

    Alternative solution:

    I created a small simple program (provided below in GitHub) that will run as a pre-build event and merge XAML files from a folder into one long .XAML file. Well, they need to be with a different extension (.txaml), otherwise they will be compiled.

    This allows to structure resources folders and files however you want, without WPF’s limitations. StaticResource and the designer will work always.

    The code in GitHub contains a simple solution that contains the merging program. It merges 2 folders into 2 files. One for App.xaml resources and the other for Generic.xaml resources. The .xaml files in a "Controls" project (There's also "Main" project).

    Blog post explaining this

    0 讨论(0)
  • 2021-01-04 18:58

    By moving the dictionaries out of App.xaml the resources from each dictionary aren't in the other's resource tree during loading of MyFirstTemplates.xaml. Your original setup first loaded ColorsDictionary which was then available through App resources to ControlsTemplatesDictionary while it loaded. In your new setup, in order for the color resource to be available in App resources it needs to be loaded through MyFirstTemplates, which in turn requires loading of both dictionaries, which in turn requires access to the color resource... so it's sort of an infinite loop of references that can't be resolved statically. DynamicResource can wait until everything is loaded and then access the color without issue.

    To fix either use Dynamic or merge ColorsDictionary directly into ControlsTemplatesDictionary.

    0 讨论(0)
提交回复
热议问题