XAML ResourceDictionary无法使用单个键集正确加载

时间:2017-05-30 15:32:10

标签: c# wpf xaml resourcedictionary

我一直在研究WPF应用程序,并且遇到了一些关于我的App.XAML文件的Application.Resources元素中定义的资源的一些相当奇怪的行为。

我真的只需要在我的ResourceDictionary中定义一个字符串资源,我尝试使用以下XAML:

<Application x:Class="MyClass.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <Application.Resources>
        <sys:String x:Key="htmlHelpFilePath">.\Help\glossary.chm</sys:String>
    </Application.Resources>
</Application>

然后尝试使用以下代码访问它:

ResourceDictionary resourceDictionary = App.Current.Resources;
string htmlHelpFile = (string)resourceDictionary["htmlHelpFilePath"];

遗憾的是,htmlHelpFile被设置为null。调试器还显示resourceDictionary具有零键集。

我开始玩游戏,发现只需在我的Application.Resource XAML元素中添加另一个资源就可以正确填充字典,所以我最终选择了:

<Application.Resources>
    <sys:String x:Key="htmlHelpFileName">glossary.chm</sys:String>
    <sys:String x:Key="htmlHelpFileDirectory">.\Help\</sys:String>
</Application.Resources>

这个解决方案按预期工作,我继续我的工作,但我绝对不知道为什么这种行为正在以它发生的方式发生。我对XAML配置WPF应用程序内部工作原理的了解非常基础,并且很想知道这种奇怪行为的原因。

1 个答案:

答案 0 :(得分:1)

这是一个已知的错误。 Ben Gribaudo在他的博客上写到了这个问题(link to full blog post)。引用这篇文章中的相关部分:

  

[...]

     

在程序的App.xaml文件中:

     
      
  • &lt; Application&gt;标记没有StartupUri属性。 (相反,程序的初始窗口是通过覆盖启动的   App.xaml.cs中的应用程序的OnStartup方法。)
  •   
  • &LT; Application.Resources&GT;包含只有一个条目
  •   
     

[...]

     

Visual Studio自动生成一个名为App.g.cs的隐藏文件,该文件将App.xaml“连接”到应用程序中。当存在上述两个因素时,代码生成器有时无法插入将&lt; Application.Resources&gt;的内容加载到应用程序中的代码。如果未发生此加载,程序中的其他XAML文件将无法使用&lt; Application.Resources&gt;中定义的资源。

(强调我的)

Microsoft Connect也有此问题的记录(link);但负责任的开发团队已经宣布这是一个“不会解决的问题”。

还有一个StackOverflow问题,其中有许多答案讨论了不同的可能的解决方法:App.xaml file does not get parsed if my app does not set a StartupUri?

您自己已经发现的一种解决方法 - 通过简单地添加第二个(虚拟)资源,避免在资源字典中只使用一个资源。