加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在水平StackLayout中居中文本?

发布时间:2020-12-15 23:28:57 所属栏目:百科 来源:网络整理
导读:我有这个StackLayout,我曾经在XAML中创建一个导航栏.此Horizo??ntal StackLayout包含一个按钮和标签.问题是文本没有完全居中,我似乎无法在中间完美地完成它.有人可以帮我把这个文本集中在这个StackLayout中吗?顺便说一下,我正在使用Xamarin. !-- Nav Bar--S
我有这个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"
                Android="0,0"
                WinPhone="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并不是很好.当你有很多观点时,这是很好的,你希望它们都以合理的方式出现.

如果你想要像素完美的东西,有两个很棒的布局:

> AbsoluteLayout
> RelativeLayout

您可以在此处找到有关这些布局的一些重要信息:http://adventuresinxamarinforms.com/2015/05/05/demystifying-xamarin-forms-absolutelayout-and-relativelayout-positioning/

对于你的具体问题,我会说使用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.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,AbsoluteLayoutFlags.All
        );
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读