引用 App.xaml 的 ResourceDictionary 时出现 IOException

IOException when referencing App.xaml's ResourceDictionary

我正在尝试从单独的 WPF window 引用 App.xaml 的 ResourceDictionary。我想在不同 windows 中使用那里的资源,这似乎是推荐的方法。不幸的是,我似乎无法从另一个 window 有效地引用 App.xaml。这是我的 App.xaml:

<Application x:Class="View.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
         xmlns:ViewModel="clr-namespace:ViewModel;assembly=ViewModel"
         xmlns:local="clr-namespace:View"
         StartupUri="ClockView.xaml">
<Application.Resources>
    <ResourceDictionary>
        <local:PriorityToIconConverter x:Key="PriorityToIconConverter" />
    </ResourceDictionary>
</Application.Resources>

注意:我没有使用 MainWindow,所以我用一个总是出现的表单替换了启动 URI。我注意到在其他一些答案中,MainWindow 的位置有时是问题所在。就我而言,我没有发现使用 ClockView 或 MainWindow 之间有任何区别。 ClockView 和 MainWindow 都存在于根命名空间中,只是从不加载 MainWindow。我还有更多资源,但为了简洁起见,我删除了它们。

这是我尝试从 App.xaml:

中引用 ResrouceDictionary 的代码的简化示例
<local:AssistantWindow 
    x:Class="View.AutomatorView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
    xmlns:properties="clr-namespace:View.Properties"
    xmlns:local="clr-namespace:View"
    mc:Ignorable="d"
    Title="Tool" 
    x:Name="Tool"
    Background="Transparent"
    Height="600"
    Width="450"
    Topmost="{Binding Source={x:Static properties:Settings.Default}, Path=ToolAlwaysOnTop}"
    MinHeight="515"
    MinWidth="150">

<Window.Resources>
    <ResourceDictionary Source="App.xaml" />
</Window.Resources>

再次强调,这是为了简洁而简化的。当我尝试加载此表单时,出现异常:

System.Windows.Markup.XamlParseException: ''Set property 'System.Windows.ResourceDictionary.Source' threw an exception.' Line number '21' and line position '10'.'

Inner Exception
IOException: Cannot locate resource 'tool/app.xaml'.

"Tool" 的视图位于也名为 "Tool." 的文件夹中,但是,xaml 和后面的代码不引用此命名空间,我只是使用用于组织我的 类 的文件夹。看起来它正在视图所在的文件夹中寻找 App.xaml。App.xaml 位于根命名空间 (View) 中。我已尝试将 xaml 中的源代码修改为 Tool 以: - 查看。App.xaml - View:App.xaml - View/App.xaml

我怎样才能让这个引用起作用,以便我可以在我的应用程序中共享资源?谢谢。

您无法像您尝试的那样加载 App.xaml,因为它实际上不是 ResourceDictionary。您只能指定 ResourceDictionary 文件作为 Source 的目标。

但是,如果您在 App.xaml 中声明资源,则可以在任何地方引用它而无需加载它所在的文件。这是自动为您完成的。因此,您可以随时使用 {StaticResource PriorityToIconConverter}.

引用您的转换器

请注意,如果您将其从默认起始位置(基础项目文件夹)移出,您可能必须更新其位置。右键单击您的项目,然后单击属性。导航到 "Application" 选项卡(应该是 left-hand 侧边栏最上面的元素)并查找 "Startup object" 字段。将其设置为 [ProjectName].[Namespace?].[Namespace?].App。当我测试它时,我的工作无需手动更改位置,但您的设置可能会有所不同。