问题描述
比方说,我想更改标签的字体.那意味着我必须写这样的东西:
Let's say, I wanna change the font of the label. That means that I'll have to write something like that:
[assembly: ExportRenderer(typeof(Label), typeof(LabelFontRenderer))]
namespace MyApp.Droid
{
public class LabelFontRenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
var label = (TextView)Control; // for example
Typeface font = Typeface.CreateFromAsset(Forms.Context.Assets, "Roboto-Regular.ttf"); // font name specified here
label.Typeface = font;
}
}
}
但是,将其添加到项目中会使所有标签以指定的字体呈现.如果我只想使用该字体渲染一些特定的标签怎么办?
However, adding that to a project will make all labels render with the specified font. What if I want to make only some, specific labels render with that font?
也许一个解决方案是从Label继承并将渲染器添加到该继承的类,从而仅将其应用于该特定类的实例,因此仅将其应用于指定的标签.因此,我的问题由两部分组成:(1)是我描述正确方法的方式,它将起作用;如果没有,(2)什么是正确方法?
Maybe a solution is to inherit from Label and add renderer to that inherited class, thus applying it only to the instances of that particular class and therefore applying it only to specified labels. Thus, my question consists of two parts: (1) is the way that I described the correct way and will it work, and if not, (2) what is the correct way?
推荐答案
这是为您的控件/需求制作自定义渲染器的正确方法.通过导出Label
类型的渲染器,您正在修改应用程序中的所有标签.
This is the correct way of doing custom renderers for your controls/needs. By exporting the renderer for Label
type, you're modifying the all the labels in the app.
您必须在共享项目中创建一个继承的Label
类,并为其定义一个自定义渲染器.例如:
You have to create a inherited Label
class in the shared project and define a custom renderer for it. For example:
在共享/便携式项目中:
In shared/portable project:
public class MyLabel : Label {}
在Android项目中:
In Android project:
[assembly: ExportRenderer(typeof(MyLabel), typeof(LabelFontRenderer))]
namespace MyApp.Droid
{
public class LabelFontRenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
var label = (TextView)Control; // for example
Typeface font = Typeface.CreateFromAsset(Forms.Context.Assets, "Roboto-Regular.ttf"); // font name specified here
label.Typeface = font;
}
}
}
用法:
var myLabel = new MyLabel { Text = "Hello" };
这篇关于如何仅将自定义渲染器添加到某些特定的布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!