首页 > 解决方案 > 未找到独立 ResourceDictionary 资源

问题描述

我关注了https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/resource-dictionaries#stand-alone-resource-dictionaries但我得到了错误。

XFC0124 找不到资源“ResourceDictionary1.xaml”。

我的代码是

ResourceDictionary1.xaml(已删除代码隐藏)编译选项:嵌入资源

<?xml version="1.0" encoding="UTF-8" ?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">

 <x:String x:Key="test">
        test string
    </x:String>

</ResourceDictionary>

ContentPage1.xaml

   <ContentPage.Resources>
        <ResourceDictionary Source="ResourceDictionary1.xaml"/>
  </ContentPage.Resources>

标签: xamlxamarin.formsresourcedictionary

解决方案


我使用链接中提供的步骤进行测试,一切正常。

检查以下步骤

  1. 添加一个ContentView文件并将其重命名为 ResourceDictionary1 。

    在此处输入图像描述

  2. 删除代码隐藏

    在此处输入图像描述

  3. 在 xaml 中删除x:Class="FormsApp.ResourceDictionary1"并将标记从 更改ContentViewResourceDictionary

<?xml version="1.0" encoding="UTF-8"?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" >
    
    
    <x:String x:Key="test">
        test string
    </x:String>
</ResourceDictionary>
  1. 在其他 xaml 中的用法

    <ContentPage.Resources>
        <ResourceDictionary Source="ResourceDictionary1.xaml"/>
    </ContentPage.Resources>
    
    
    <ContentPage.Content>
        <StackLayout>
            <Button Clicked="Button_Clicked" Text="{StaticResource test}"/>
        </StackLayout>
    </ContentPage.Content>

在此处输入图像描述


如果您已完成上述所有步骤,但问题仍然存在,则一定是文件路径有问题。

ResourceDictionary文件应与使用 ResourceDictionary 的页面位于同一级别。

  • 我们可以将它们放在表单项目的根目录中。

    在此处输入图像描述

  • 我们可以将它们放在同一个文件夹中。

    在此处输入图像描述

  • 如果它们不在同一级别,我们应该在页面中设置相对文件路径。

    在此处输入图像描述

   // in page4.xaml
    <ContentPage.Resources>
        <ResourceDictionary Source="MyFolder/ResourceDictionary1.xaml"/>
    </ContentPage.Resources>

推荐阅读