Though you can't stretch label's text to a full width using Xamarin.Forms features, it's easily achieved with a platform renderer.
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
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;
}
}
}
}
}
- Your create renderer class in native project
- You add assembly: ExportRenderer attribute
- You set TextView's JustificationMode
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); }
}
}
}
- Examples of platform renderers for WPF and macOS.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…