fdkgfosfskjdlsjdlkfsf
fdkgfosfskjdlsjdlkfsf

Reputation: 3303

Xamarin.Forms: Add padding to label in grid?

A grid cell looks like this:

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

There are 2 columns, and each column is 50% of the width. With the xaml above, the whole cell (half the row) will be painted red.

It looks like this:

enter image description here

Can I add left and/or right padding just to Grid.Row="0" and Grid.Column="1" so that the column is still 50% width but not the label? What I don't want to do is change the grid structure (ie. add more columns).

The desired result is something like this, but without having to add more columns or change column size:

enter image description here

Upvotes: 0

Views: 2035

Answers (3)

Lucas Zhang
Lucas Zhang

Reputation: 18861

You can put the label in a StackLayout and set the padding of it.Such as:

<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:Differernt from padding in CSS (top-right-buttom-left),the order of the padding in xamarin is left-top-right-buttom.

For more detail you can refer Margin and Padding

Upvotes: 2

Armin Rasoulian
Armin Rasoulian

Reputation: 301

Just add HorizontalOptions="Center" if you just want to place in the middle of the column. In this method, if the label's text is increased, the space around the label decreases.

If you want to have a certain amount of space around the label, you should set Margin for Label.

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

Upvotes: 2

Aritra Das
Aritra Das

Reputation: 272

If I understood that correctly you need margin and not padding. For the very same reason, you won't find a padding property in Label, like many other views in Xamarin Forms.

This should serve your purpose.

<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" />

To understand how padding and margin works in details, you can check this link https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/layouts/margin-and-padding

Upvotes: 0

Related Questions