gpt4 book ai didi

c# - 如何在 Horizo​​ntal StackLayout 中将文本居中?

转载 作者:太空宇宙 更新时间:2023-11-03 12:16:29 25 4
gpt4 key购买 nike

我有这个 StackLayout,我曾用它在 XAML 中创建导航栏。这个 Horizo​​ntal 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>

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

最佳答案

当您想将 View 放在特定位置时,StackLayout 不是很好。当您有多个 View 并且希望它们都以合理的方式显示时,这很好。

当您想要像素完美的东西时,有两种很棒的布局:

  • 绝对布局
  • 相对布局

对于您的具体问题,我会说使用 AbsoluteLayout,因为它非常容易将 Label 居中。对于此解决方案,我将 Nav Bar 的 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
);
}

关于c# - 如何在 Horizo​​ntal StackLayout 中将文本居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33808250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com