引用App.xaml的ResourceDictionary

时间:2019-06-05 23:34:34

标签: wpf xaml app-config

我正在尝试从单独的WPF窗口引用App.xaml的ResourceDictionary。我想在不同的窗口中使用资源,这似乎是推荐的方法。不幸的是,我似乎无法从其他窗口中有效引用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'.

“工具”的视图位于也称为“工具”的文件夹中。但是,后面的xaml和代码没有引用此命名空间,我只是使用文件夹来组织我的课程。看起来好像在视图所在的文件夹中寻找App.xaml。App.xaml驻留在根名称空间(视图)中。我尝试将xaml for Tool中的源修改为: -View.App.xaml -查看:App.xaml -查看/App.xaml

如何获得此参考资料,以便可以在整个应用程序中共享资源?谢谢。

1 个答案:

答案 0 :(得分:1)

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

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

请注意,如果将其从默认起始位置(基础项目文件夹)中移出,则 可能必须更新其位置。右键单击您的项目,然后单击属性。导航到“应用程序”选项卡(应位于左侧边栏的最上方),然后查找“启动对象”字段。将其设置为[ProjectName].[Namespace?].[Namespace?].App。当我对其进行测试时,我的工作无需手动更改位置,但是您的设置可能有所不同。