【问题标题】:Getting Cannot convert to Xamarin.Forms.Element error when trying to create custom ResourceDictionary尝试创建自定义 ResourceDictionary 时出现无法转换为 Xamarin.Forms.Element 错误
【发布时间】:2018-08-03 16:14:39
【问题描述】:

我正在尝试将样式分成多个 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

App.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 模板。

【问题讨论】:

  • 在编译 App.xaml 或 RedTheme.xaml 时是否遇到编译错误?

标签: c# visual-studio xaml xamarin xamarin.forms


【解决方案1】:

可以使用 XML 文件模板:

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

App.xaml merged ResourceDictionary in 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>

【讨论】:

    【解决方案2】:

    您忘记在样式中添加 x:key。这就是为什么你得到那个例外。

    【讨论】:

      猜你喜欢
      • 2014-03-10
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-07
      • 1970-01-01
      • 2017-06-02
      • 2020-04-10
      相关资源
      最近更新 更多