【问题标题】:Xamarin.Forms: Add padding to label in grid?Xamarin.Forms:向网格中的标签添加填充?
【发布时间】:2019-07-21 20:21:15
【问题描述】:

网格单元如下所示:

<Label Text="{Binding Name}" 
       Grid.Row="0" 
       Grid.Column="1" 
       VerticalTextAlignment="Center" 
       HorizontalTextAlignment="Center" 
       FontSize="16" 
       TextColor="White" 
       BackgroundColor="red" />

有 2 列,每列是宽度的 50%。使用上面的 xaml,整个单元格(行的一半)将被涂成红色。

看起来像这样:

我可以在Grid.Row="0"Grid.Column="1" 中添加左和/或右填充,这样列仍然是 50% 的宽度,而不是标签?我不想做的是更改网格结构(即添加更多列)。

想要的结果是这样的,但无需添加更多列或更改列大小:

【问题讨论】:

  • 只是将填充或边距值添加到标签?我不确定你到底想做什么
  • 我已编辑问题以显示我希望结果的样子。
  • 我猜它就像 CSS 中的 padding-leftpadding-right 属性。
  • 您可以尝试在该标签中应用 Horizo​​ntalOptions="StartAndExpand" 以便它仅扩展其中的文本,或者如果您只想要那么多空间,则为该标签提供固定宽度应用 LineBreakMode。
  • 嘿,你的问题解决了吗?

标签: xamarin xamarin.forms visual-studio-2017


【解决方案1】:

您可以将标签放在StackLayout 中并设置它的填充。例如:

<StackLayout Grid.Row="0" Grid.Column="1" Padding="10,0,10,0">
  <Label  
        Text="text"  
        VerticalTextAlignment="Center" 
        HorizontalTextAlignment="Center" 
        FontSize="16" 
        TextColor="White" 
        BackgroundColor="red" />
</StackLayout>

PS:不同于CSS中的padding(top-right-buttom-left),xamarin中padding的顺序是left-top-right-buttom。

更多详情可以参考Margin and Padding

【讨论】:

    【解决方案2】:

    如果我理解正确,您需要边距而不是填充。出于同样的原因,您不会在 Label 中找到 padding 属性,就像 Xamarin Forms 中的许多其他视图一样。

    这应该符合您的目的。

    <Label Text="{Binding Name}" 
           Grid.Row="0" 
           Grid.Column="1"
           Margin="20, 0, 20, 0" 
           VerticalTextAlignment="Center" 
           HorizontalTextAlignment="Center" 
           FontSize="16" 
           TextColor="White" 
           BackgroundColor="red" />
    

    要详细了解内边距和边距的工作原理,您可以查看此链接 https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/layouts/margin-and-padding

    【讨论】:

      【解决方案3】:

      如果您只想放在列的中间,只需添加HorizontalOptions="Center"。在这种方法中,如果标签的文本增加,标签周围的空间就会减少。

      如果你想在标签周围留出一定的空间,你应该为标签设置Margin

      <Label Text="{Binding Name}" 
             Grid.Row="0" 
             Grid.Column="1" 
             Margin="20,0"
             VerticalTextAlignment="Center" 
             HorizontalTextAlignment="Center" 
             FontSize="16" 
             TextColor="White" 
             BackgroundColor="red" />
      

      【讨论】:

      • 您能否添加示例说明如何使用Margin 作为标签?
      • 我添加了一个例子。
      猜你喜欢
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-02
      • 2021-09-15
      相关资源
      最近更新 更多