首页 > 解决方案 > 从 ContentView 访问 App.xaml 中的全局资源

问题描述

我在 App.xaml 资源字典中定义了一种颜色。当我尝试在 ContentView 中引用它时,出现运行时异常:

未找到键 NavbarBackground 的 StaticResource

我需要在 App.xaml 中合并资源字典吗?

应用程序.xaml
<Application.Resources>
    <ResourceDictionary>
        <!--Global Styles-->
        ...
        <Color x:Key="NavbarBackground">Black</Color>
        ...
    </ResourceDictionary>
</Application.Resources>
CustomTitleView.xaml
<ContentView>
    ...
    <ContentView.Content>
         ...
                <ImageButton Source="search.png" HorizontalOptions="Center"
                    VerticalOptions="CenterAndExpand" BackgroundColor="{StaticResource NavbarBackground}" />
         ...
     </ContentView.Content>
</ContentView>

标签: xamarinxamarin.formsxamarin.androidxamarin.ios

解决方案


如果您使用单独的 xaml 文件来定义资源,请使用 ResourceDictionary。如果您是 App.xaml 中的设置值,请将它们设置在 Application.Resources 中。请参阅此处的文档


推荐阅读