如何在水平堆叠布局中使文本居中?

6

我有一个 StackLayout,用于在 XAML 中创建导航栏。这个水平的 StackLayout 包含一个按钮和标签。问题是文本并不完全居中,我似乎无法将其完美地放置在中间。请有人帮我将此文本居中在此 StackLayout 中吗?顺便说一下,我正在使用 Xamarin。

<!-- Nav Bar-->
<StackLayout Orientation="Horizontal" HeightRequest="45" BackgroundColor="{StaticResource Teal}">
  <StackLayout.Padding>
    <OnPlatform x:TypeArguments="Thickness"
                iOS="10,0,0,0"
                Android="0,0,0,0"
                WinPhone="0,0,0,0" />
  </StackLayout.Padding>
  <Button x:Name="btnBack" HorizontalOptions="Start" TextColor="White" BackgroundColor="Transparent"
          Command="{Binding BackCommand}" IsVisible="{Binding CanGoBack}" />
  <Label HorizontalOptions="CenterAndExpand" VerticalOptions="Center" TextColor="White" FontSize="24" Text="{Binding TitleBarText}" LineBreakMode="TailTruncation" />
</StackLayout>

如您所见,应用程序标题未居中...


1
“Label”在减去按钮后的剩余空间中居中显示,这是StackLayout的工作原理。使用不同类型的布局可能更容易实现此目标。我认为AbsoluteLayout或RelativeLayout在这种情况下会更好地发挥作用。如果您愿意,我可以发布一个答案来说明如何实现这一点。 - dylansturg
嘿,谢谢!我真的卡在这里了,所以你的帮助会是一个非常大的帮助。 - stepheaw
2个回答

10

如果你想将视图放在特定位置,StackLayout并不是最好的选择。但是当你需要展示多个视图,并且希望它们以合理的方式出现时,StackLayout是很好的选择。

如果你想要像素级别的精确控制,有两种很棒的布局:

  • AbsoluteLayout
  • RelativeLayout

针对你的具体问题,我建议使用AbsoluteLayout,因为它非常容易让Label居中显示。为了解决这个问题,我将你的导航栏StackLayout更改为AbsoluteLayout,并在代码后台添加了布局参数。

XAML代码:

<AbsoluteLayout x:Name="NavBarLayout" HeightRequest="45" BackgroundColor="Aqua">
     <Button x:Name="btnBack" TextColor="White" FontSize="40" BackgroundColor="Transparent" Text="&lt;" />
     <Label x:Name="labelTitle" TextColor="White" FontSize="24" Text="Hello World!" YAlign="Center" XAlign="Center" LineBreakMode="TailTruncation" />
</AbsoluteLayout>

背后的代码:

public MyPage ()
    {
        InitializeComponent ();

        NavBarLayout.Children.Add (
            btnBack,
            // Adds the Button on the top left corner, with 10% of the navbar's width and 100% height
            new Rectangle(0, 0, 0.1, 1),
            // The proportional flags tell the layout to scale the value using [0, 1] -> [0%, 100%]
            AbsoluteLayoutFlags.HeightProportional | AbsoluteLayoutFlags.WidthProportional
        );

        NavBarLayout.Children.Add(
            labelTitle,
            // Using 0.5 will center it and the layout takes the size of the element into account
            // 0.5 will center, 1 will right align
            // Adds in the center, with 90% of the navbar's width and 100% of height
            new Rectangle(0.5, 0.5, 0.9, 1),
            AbsoluteLayoutFlags.All
        );
    }

这绝对是我正在寻找的解决方案。非常感谢。 - stepheaw

5

我知道这是一个非常古老的帖子,但对于仍然遇到类似问题的人来说,我使用以下方法解决了它:

 HorizontalOptions="Center"

关于 XAML 中的 StackLayout 定义。我使用的完整定义如下:

<StackLayout Spacing="5" Orientation="Horizontal" x:Name="ButtonLayout" HorizontalOptions="Center">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接