XAML 在WPF应用程序中找不到资源字典

cbeh67ev  于 12个月前  发布在  其他
关注(0)|答案(5)|浏览(230)

我正在构建一个WPF应用程序,在尝试引用资源字典时遇到了一个错误。在我的WPF应用程序项目中,我有一个名为“Styles”的文件夹,其中包含我的应用程序的所有xaml样式模板:

在我的app.xaml文件中,我有这个:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Styles/MetroTheme.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

然而,当我将鼠标悬停在source属性上时,我得到一个错误,说“Anerror occurred while finding the resource dictionary“Styles/MetroTheme.xaml”。我可以在Visual Studio和文件系统中的文件夹中看到xaml文件。
我还尝试了“/Styles/MetroTheme.xaml”和源属性的packURI,但都没有成功。任何想法,为什么我得到这个文件找不到错误?

klh5stk1

klh5stk11#

我也遇到了同样的问题,但是设置 * Build Action = Page * 并没有解决我的问题。我需要使用Pack URI Format。所以,

<ResourceDictionary Source="pack://application:,,,/Styles/MetroTheme.xaml"/>

编辑

事实证明,上述方法可以消除构建错误,但仍然会导致运行时错误。我需要包括完整的程序集规范以获得完整的解决方案(即使所有文件都在同一个程序集中):

<ResourceDictionary Source="pack://application:,,,/WpfApplication10;component/Styles/MetroTheme.xaml"/>
q9rjltbz

q9rjltbz2#

确保MetroTheme.xaml的构建操作设置为Page。

uurity8g

uurity8g3#

有时关闭Visual Studio并再次打开它可以解决此问题。

8ulbf1ek

8ulbf1ek4#

我确认它是因为相对uri上的一些奇怪行为。
举例来说:
/SubProjectDir/WhatThingDir/YourResource.xaml

<ResourceDictionary>
   <SolidColorBrush x:Key="TheBrush" Color="Black" />
</ResourceDictionary>

/SubProjectDir/AnotherDir/YourControl.xaml

...
<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/WhatThingDir/YourResource.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
...

/MainExecution/MainWindow.xaml

...
<sub:YourControl />
...

它看起来在设计师工作得很好。但是当你运行它的时候,会抛出找不到资源的异常。
因为/WhatThingDir/YourResource.xaml的意思是“从当前根路径查找相关资源”,但是现在MainWindow构造了YourControl,所以当前根路径MainExecution下开始。然后,它尝试在MainExecution中找到资源路径/WhatThingDir/YourResource.xaml。一定失败了!
但如果你写这个,它会工作得很好:
/SubProjectDir/AnotherDir/YourControl.xaml

...
<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="../WhatThingDir/YourResource.xaml" />
<!--                           Here ^^^ Here                          -->
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
...

这将在/SubProjectDir/AnotherDir/../WhatThingDir/YourResource.xaml => /SubProjectDir/WhatThingDir/YourResource.xaml中查找资源。
没事了!

rpppsulh

rpppsulh5#

在项目属性中将目标.net版本更改为旧版本,然后重置为以前的版本。

相关问题