Why are absolute uri's required for merged dic

2019-04-05 15:28发布

Consider a File | New Project of a WPF Application that contains:

  1. A new custom control named CustomControl1
  2. Two new resource dictionaries named Dictionary1 and Dictionary2

Take the generated style out of Generic.xaml and move it to Dictionary2. Then merge Dictionary2 into Dictionary1 and Dictionary1 into Generic like this:

<!--Generic.xaml-->
<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="pack://application:,,,/Themes/Dictionary1.xaml"/>
</ResourceDictionary.MergedDictionaries>

<!--Dictionary1.xaml-->
<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="Dictionary2.xaml"/>
</ResourceDictionary.MergedDictionaries>

Then, add an instance of CustomControl1 into MainWindow's grid. (This part is necessary to reproduce the issue. The project always compiles fine - only at runtime does the issue show up, and the dictionaries must be referenced.)

In Dictionary1.xaml I am merging in another dict in the same folder, so a simple Source="Dictionary2.xaml" works. Yet in Generic.xaml I must use an absolute URI. If I change the above to be Source="Dictionary1.xaml" without the pack://application stuff then I get a XamlParseException caused by an IOException "Cannot locate resource 'dictionary1.xaml'" when it tries to construct the MainWindow.

My Question: What's special about generic.xaml regarding relative URI resolution, and why?

2条回答
看我几分像从前
2楼-- · 2019-04-05 15:36

Just a guess: generic.xaml needs to be accessible from outside assemblies as well, so it's a way to ensure that the resources can be found from anywhere, using absolute URIs. As I said, it's just a stab in the dark, not sure.

查看更多
成全新的幸福
3楼-- · 2019-04-05 15:45

Excuse me because I have no ability to write comments so I post this as an answer.

I have the same situation and everything works fine for me. I don't need to put "pack://application" in the path in Generic.xaml. But only when the output type of an assembly is "Windows Application". For "Class library" I need to add assembly name to the path (Source="/ClassLibarayAssemblyName;component/Themes/Dictionary1.xaml") becasue without it WPF engine tries to look for Dictionary1.xaml in application's main assembly.

Target framework in both cases is ".NET Framework 4 Client Profile"

查看更多
登录 后发表回答