代码之家  ›  专栏  ›  技术社区  ›  Noobie3001

尝试创建自定义资源字典时,获取无法转换为Xamarin.Forms.Element错误

  •  0
  • Noobie3001  · 技术社区  · 8 年前

    我正在尝试将样式分为多个资源字典文件。根据文档,我应该创建一个内容视图或内容页,并将其更改为从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>
    

    红色主题.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>
    

    红色主题.xaml.cs

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

    这在Visual Studio中不起作用吗?Visual Studio的“添加新文件”菜单中也没有资源信息模板。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Benl    8 年前

    可以使用XML文件模板:

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

    应用程序.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>