c# - 尝试创建自定义 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 模板。
解决方案
可以使用 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>
推荐阅读
- python - 如何从 SQL Server MS 执行外部 python 脚本文件(托管在远程桌面上)
- node.js - listObjectsV2 使用 nodejs 列出嵌套“文件夹”中的所有对象
- github - 你能从终端触发一个 github webhook
- r - 如何用包latex2exp在xlab中做概率符号?
- bash - 自动重新启动已终止的作业 [bash]
- python - 未捕获的类型错误:无法读取未定义的属性(读取“开始”)
- bayesian - 如何在贝叶斯先验上将下限指定为 0
- reactjs - 在 Javascrip React 中创建 BcG 矩阵
- bash - 如何在bash中提取字符串?
- vue.js - 模型名称的 Prop 无效,字符串输入显示为“未定义”