【发布时间】:2017-03-14 20:10:00
【问题描述】:
我对 Xaml 很陌生,但我遇到了一个问题。我想在我的应用程序中使用 FontAwesome 图标,按照教程后,我可以以编程方式使用图标(代码如下)。
Content = new StackLayout
{
Children = {
new FontIcon(FontIcon.Icon.Globe) {TextColor=Color.Red }
},
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand,
};
但是,当我尝试在 Xaml 中实现这一点时 - 它会使我的应用程序崩溃。
共享类扩展标签代码:
using Xamarin.Forms;
namespace myApp.Fonts
{
public class FontIcon : Label
{
public const string Typeface = "FontAwesome";
public FontIcon(string faIcon = null)
{
FontFamily = Typeface;
Text = faIcon;
}
public static class Icon
{
public static readonly string Gear = "";
public static readonly string Globe = "\uf000";
}
}
}
Xaml 代码...请注意,我已经将 xmlns:local 用于另一个类
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="myApp.TestPage"
xmlns:ctt="clr-namespace:myApp.Fonts">
<ctt:FontIcon FontIcon ="\uf000" VerticalOptions="Center" HorizontalOptions="Center" />
我猜问题出在这一行:
<ctt:FontIcon FontIcon ="\uf000" VerticalOptions="Center" HorizontalOptions="Center" />
我不确定如何通过 xaml 访问该类,或者是否可以使用 xlmns:ctt
编辑---------------------------------------------- ---------------------------
我使用了调试,这是实际错误:
System.MissingMethodException:找不到类型 myApp.Fonts.FontIcon 的默认构造函数
编辑 2:
我这样做了:
public FAIcon()
{
}
在 xaml 中:
<custom:FAIcon FontFamily = "Typeface" Text = "\uf000" VerticalOptions="Center" HorizontalOptions="Center" />
应用程序现在不会崩溃,但会显示纯文本而不是图标
这是我的安卓渲染器:
[assembly: ExportRenderer(typeof(FontIcon), typeof(FARenderer))]
namespace myApp.Droid.Renderers
{
public class FARenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
if (e.OldElement == null)
{
Control.Typeface = Typeface.CreateFromAsset(Forms.Context.Assets, FontIcon.Typeface + ".ttf");
}
}
}
}
【问题讨论】:
-
什么不起作用?
-
-
它让我的应用程序崩溃了。 myApp.Droid 已停止工作 - 我正在尝试调试以查看实际错误
-
XAML 需要无参数构造函数。
-
@Jimmy XAML 中使用的任何对象都必须有一个空构造函数,因此
public FontIcon(){...}you 将元素中的属性设置为VerticalOptions="Center"