c# Xaml -使用自定义类-以编程方式工作,但不能在Xaml中工作
本文关键字:工作 Xaml 但不能 方式 自定义 编程 | 更新日期: 2023-09-27 18:15:53
我是Xaml的新手,我面临一个问题。我想在我的应用程序中使用fontaawesome图标,在遵循教程之后,我可以以编程方式使用图标(下面的代码)。
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
编辑 -------------------------------------------------------------------------
我用的是debug,下面是实际的错误:
系统。MissingMethodException: myApp.Fonts.FontIcon类型的默认构造函数未找到
编辑2:
我这样做了:
public FAIcon()
{
}
和xaml:
<custom:FAIcon FontFamily = "Typeface" Text = "'uf000" VerticalOptions="Center" HorizontalOptions="Center" />
应用程序现在不会崩溃,但它显示纯文本而不是图标
这是我的android渲染器:[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");
}
}
}
}
如果你总是想使用FontAwesome,在你的构造函数中设置它:
public const string Typeface = "FontAwesome";
public FAIcon()
{
FontFamily = TypeFace;
}
不要在你的XAML中这样做,它只是将FontFamily设置为"TypeFace"这不是你想要的
<custom:FAIcon FontFamily = "Typeface" ...