问题
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?
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?
回答1:
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.
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.
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 {}
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;
}
}
}
Usage:
var myLabel = new MyLabel { Text = "Hello" };
来源:https://stackoverflow.com/questions/38781477/how-to-add-custom-renderers-to-only-some-specific-layouts