Xamarin 表单标签 - 证明? [英] Xamarin Forms Label - Justify?
问题描述
我只是想问问是否有任何方法可以在 标签 中对齐文本.我正在使用 Xamarin Forms Xaml.
I just wanted to ask if there is any way to justify text in a Label. I am using Xamarin Forms Xaml.
谢谢.
更新:就目前而言,无法对齐文本.大多数答案都是关于将文本居中,但这不是我问的.一种方法是使用 Timothy 的 Renderer.
UPDATE: As for now, it is not possible to justify text. Most of the answers were about centering the text, but it is not what I asked. One way could be to use Renderer as by Timothy.
推荐答案
虽然您无法使用 Xamarin.Forms 功能将标签的文本拉伸到全宽,但可以使用平台渲染器轻松实现.
Though you can't stretch label's text to a full width using Xamarin.Forms features, it's easily achieved with a platform renderer.
大多数 Xamarin 平台都在相应的本机元素中提供了文本对齐功能,这只是设置本机元素的单个属性的问题.我想不将此功能添加到标准 Xamarin.Forms 标签的原因是该功能的平台滞后,例如Android 仅在 8.1 版中添加了 Android.Text.JustificationMode.InterWord 标志
Most Xamarin platforms have the text justification feature available in corresponding native elements, and it's just a matter of setting a single attribute of a native element. I suppose the reason for not adding this feature to standard Xamarin.Forms label is lagging of platforms in that capability, e.g. Android had Android.Text.JustificationMode.InterWord flag added only in version 8.1
下面你可以看到Android渲染器的实现:
Below you can see Android renderer implementation:
using Android.Content;
using Saplin.CPDT.UICore.Controls;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(Saplin.CPDT.UICore.Controls.ExtendedLabel), typeof(Saplin.CPDT.Droid.ExtnededLabelRenderer))]
namespace Saplin.CPDT.Droid
{
public class ExtnededLabelRenderer : Xamarin.Forms.Platform.Android.LabelRenderer
{
public ExtnededLabelRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
var el = (Element as ExtendedLabel);
if (el != null && el.JustifyText)
{
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
{
Control.JustificationMode = Android.Text.JustificationMode.InterWord;
}
}
}
}
}
- 您在本机项目中创建渲染器类
- 您添加程序集:ExportRenderer 属性
- 您设置了 TextView 的 JustificationMode
在我的示例中,我使用了 Xamarin.Forms.Label 的 ExtenedLabel 子类和额外的属性 JustifyText 来设置文本的对齐方式.这就是子类控件的声明方式:
In my example I used ExtenedLabel subclass of Xamarin.Forms.Label with extra property JustifyText to let setting the justification of the text. That's how the subclassed control can be declared:
using System;
using Xamarin.Forms;
namespace Saplin.CPDT.UICore.Controls
{
public class ExtendedLabel : Label
{
public static readonly BindableProperty JustifyTextProperty =
BindableProperty.Create(
propertyName: nameof(JustifyText),
returnType: typeof(Boolean),
declaringType: typeof(ExtendedLabel),
defaultValue: false,
defaultBindingMode: BindingMode.OneWay
);
public bool JustifyText
{
get { return (Boolean)GetValue(JustifyTextProperty); }
set { SetValue(JustifyTextProperty, value); }
}
}
}
- WPF的平台渲染器示例a> 和 macOS.莉>
这篇关于Xamarin 表单标签 - 证明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!