Xamarin表格标签 - 对齐?

ain*_*ner 6 xaml label justify text-alignment xamarin

我只是想询问是否有什么办法可以调整文字标签.我正在使用Xamarin Forms Xaml.

谢谢.

更新: 至于现在,不可能证明文本的合理性.大多数答案都是关于文本的中心,但这不是我的要求.一种方法是使用渲染器作为提摩太.

Max*_*lin 11

虽然您无法使用 Xamarin.Forms 功能将标签的文本拉伸到全宽,但可以使用平台渲染器轻松实现。

Xamarin.Froms 标签中的 Android 文本对齐

大多数 Xamarin 平台在相应的本机元素中都有可用的文本对齐功能,这只是设置本机元素的单个属性的问题。我想不将此功能添加到标准 Xamarin.Forms 标签的原因是该功能的平台滞后,例如 Android 有Android.Text.JustificationMode.InterWord仅在 8.1 版中添加标志

下面你可以看到Android渲染器的实现:

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;
                }

            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 您在本机项目中创建渲染器类
  2. 您添加程序集:ExportRenderer属性
  3. 你设置 TextView 的 JustificationMode

在我的示例中,我使用Xamarin.Forms.Label 的 ExtenedLabel子类和额外的属性JustifyText来设置文本的对齐方式。这就是子类控件的声明方式:

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); }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Tim*_*ell 6

目前的方法是使用HorizontalTextAlignmentTextAlignment枚举的值是:

  • Center =居中对齐的文字
  • Start =左对齐
  • End =右对齐

将标签及其文本示例居中:

<Label x:Name="Description" HorizontalTextAlignment="Center" VerticalOptions="Center" HorizontalOptions="Center" />