首页 > 解决方案 > 尝试创建自定义 ResourceDictionary 时出现无法转换为 Xamarin.Forms.Element 错误

问题描述

我正在尝试将样式分成多个 ResourceDictionary 文件。根据文档,我应该创建一个内容视图或内容页面并将其更改为从 ResourceDictionary 继承。

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/resource-dictionaries

要创建这样的文件,请将新的内容视图或内容页面项目添加到项目(但不是只有 C# 文件的内容视图或内容页面)。在 XAML 文件和 C# 文件中,将基类的名称从 ContentView 或 ContentPage 更改为 ResourceDictionary。在 XAML 文件中,基类的名称是顶级元素。

我收到编译错误:

无法从 MyApp1.Themes.RedTheme 转换为 Xamarin.Forms.Element

应用程序.xaml

<Application.Resources>
    <ResourceDictionary >
        <ResourceDictionary.MergedDictionaries>
            <themes:ThemeBlue></themes:ThemeBlue>
            <themes:ThemeRed></themes:ThemeRed>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

RedTheme.xaml

<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms" 
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="MyApp1.Themes.RedTheme"
         x:Name="redtheme">

    <Style TargetType="Label">
        <Setter Property="TextColor" Value="Black"></Setter>
    </Style>

</ResourceDictionary>

RedTheme.xaml.cs

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class RedTheme : ResourceDictionary
{
    public RedTheme()
    {
        InitializeComponent ();
    }
}

这在 Visual Studio 中不起作用吗?在 Visual Studio 的添加新文件菜单中也没有 ResouceDictionary 模板。

标签: c#visual-studioxamlxamarinxamarin.forms

解决方案


可以使用 XML 文件模板:

添加新项目 > 已安装 > Visual C# 项目 > 数据 > XML 文件

App.xaml合并ResourceDictionary到 Xamarin.Forms 3.0 中

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="MyResourceDictionary.xaml" />
    ...

MyResourceDictionary.xaml,.xaml.cs不需要:

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

推荐阅读