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

如何正确使用自定义渲染器调整Xamarin Forms UWP Entry垂直居中

Xamarin Forms UWP Entry垂直居中生效补充配置
  • 补全UWP App.xaml中自定义样式的缺失配置
    你当前定义的TextBoxStyle1仅为ScrollViewer和HeaderContentPresenter添加了VerticalAlignment="Center",遗漏了占位符文本容器PlaceholderTextContentPresenter,需要给该节点补充对应属性,修改后的节点代码如下:
    <TextBlock x:Name="PlaceholderTextContentPresenter" 
        VerticalAlignment="Center"
        Grid.ColumnSpan="2" 
        Foreground="{Binding PlaceholderForeground, RelativeSource={RelativeSource Mode=TemplatedParent}, TargetNullValue={ThemeResource TextControlPlaceholderForeground}}" 
        IsHitTestVisible="False" 
        Margin="{TemplateBinding BorderThickness}" 
        Padding="{TemplateBinding Padding}" 
        Grid.Row="1" 
        Text="{TemplateBinding PlaceholderText}" 
        TextWrapping="{TemplateBinding TextWrapping}" 
        TextAlignment="{TemplateBinding TextAlignment}"/>
    
  • 调整自定义渲染器的配置逻辑
    在渲染器的OnElementChanged方法中补充垂直内容对齐、内边距配置,避免默认内边距挤压文本导致显示偏下,修改后的代码如下:
    [assembly: ExportRenderer(typeof(Entry), typeof(CustomTextBoxRenderer))]
    namespace Prism.PointOfSale.UWP
    {
        public class CustomTextBoxRenderer : EntryRenderer
        {
            protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
            {
                base.OnElementChanged(e);
    
                if (this.Control != null)
                {
                    this.Control.Height = 60;
                    // 补充垂直内容对齐配置
                    this.Control.VerticalContentAlignment = Windows.UI.Xaml.VerticalAlignment.Center;
                    // 调整上下内边距为0,避免挤压文本位置
                    this.Control.Padding = new Windows.UI.Xaml.Thickness(8, 0, 8, 0);
                    Control.Style = (Windows.UI.Xaml.Style)App.Current.Resources["TextBoxStyle1"];
                }
            }
        }
    }
    
  • 同步共享项目中Entry控件的属性
    在Xamarin Forms共享项目的Entry声明处,显式设置VerticalTextAlignment="Center",避免Xamarin框架的默认属性覆盖原生对齐配置。
  • 可选优化:解决编译卡顿问题
    编译卡顿大概率是自定义样式资源查找耗时导致,你可以删除样式的x:Key="TextBoxStyle1"属性,将其改为隐式样式,所有UWP平台的TextBox会自动应用该样式,同时可以删除渲染器中手动赋值Style的代码,减少资源查找开销。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 08:45:01