You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在UWP平台的Xamarin Forms Entry中垂直居中文本?

解决Xamarin.Forms 2.5 Entry控件文本垂直居中的问题

嘿,我之前在Xamarin.Forms 2.5项目里也碰到过一模一样的问题——设置HeightRequest后文本跑到控件顶部,自定义渲染器还搞砸了高度设置。下面给你分平台的靠谱解决方案,亲测有效:

Android平台自定义渲染器

Android原生的EditText默认文本是顶部对齐的,而且如果自定义渲染器写法不对,会覆盖掉XAML里的HeightRequest。你可以这样写:

using Android.Content;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(Entry), typeof(CenteredEntryRenderer))]
namespace YourAppNamespace.Droid.Renderers
{
    public class CenteredEntryRenderer : EntryRenderer
    {
        public CenteredEntryRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);

            if (Control != null && Element != null)
            {
                // 让文本垂直居中
                Control.Gravity = Android.Views.GravityFlags.CenterVertical;
                
                // 确保XAML里的HeightRequest生效
                Control.SetMinimumHeight((int)Element.HeightRequest);
                Control.LayoutParameters.Height = (int)Element.HeightRequest;
            }
        }
    }
}

iOS平台自定义渲染器

iOS的UITextField默认也是顶部对齐,需要设置垂直对齐方式,同时也要保留XAML的高度设置:

using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(Entry), typeof(CenteredEntryRenderer))]
namespace YourAppNamespace.iOS.Renderers
{
    public class CenteredEntryRenderer : EntryRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);

            if (Control != null && Element != null)
            {
                // 设置文本垂直居中
                Control.ContentVerticalAlignment = UIControlContentVerticalAlignment.Center;
                
                // 确保HeightRequest生效
                Control.HeightAnchor.ConstraintEqualTo(Element.HeightRequest).Active = true;
            }
        }
    }
}

备选方案:不用自定义渲染器(快速临时解决)

如果不想写渲染器,也可以通过设置Padding来调整文本位置,比如:

<Entry HeightRequest="60" Padding="0,15,0,15" />

这种方式是通过上下内边距把文本挤到中间,缺点是硬编码了内边距值,不同高度的Entry需要手动调整,但胜在快速简单。

注意事项

  • 记得在各自平台的项目里添加渲染器类,并且命名空间要匹配你的项目结构。
  • 如果你的Entry是自定义子类,记得把渲染器里的typeof(Entry)改成你的自定义Entry类型。
  • Xamarin.Forms 2.5版本比较老,上面的代码都是针对该版本兼容的写法,避免了高版本API的使用。

内容的提问来源于stack exchange,提问作者aritchie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:26:32