Search code examples
xamarin.formssearchbarstacklayout

How to add padding to SearchBar inside Horizontal StackLayout?


For some purpose I want to position SearchBar inside StackLayout whose Orientation is Horizontal and add padding to that StackLayout but I found that the SearchBar takes all the Width space as shown in second SearchBar while when the Orientation is Vertical it works normally as shown in first SearchBar the below image:

enter image description here

Here is the code for both StackLayouts:

    <StackLayout Orientation="Vertical" Padding="100,0,100,0">
        <SearchBar/>
    </StackLayout>

    <StackLayout Orientation="Horizontal" Padding="100,0,100,0">
        <SearchBar/>
    </StackLayout>

I also tried to put the Horizontal-Orientated StackLayout into a Vertcal-Orientated StackLayout as shown in code below:

    <StackLayout Orientation="Vertical" Padding="100,0,100,0">
        <StackLayout Orientation="Horizontal">
            <SearchBar/>
        </StackLayout>
    </StackLayout>

But it does not help too, So how to solve that problem?


Solution

  • Cause: When you add a searchBar in stackLayout ,stackLayout will not make the subview fit the size. So though you set the padding .The searchBar will still Beyond the border of stackLayout.

    Solution:

    Put the srachBar in a Grid.

    <StackLayout  Orientation="Horizontal"  Padding="100,0,100,0">
      <Grid>
        <Grid.RowDefinitions>
          <RowDefinition Height="*" /> 
        </Grid.RowDefinitions>
    
       <Grid.ColumnDefinitions>
          <ColumnDefinition Width="175" />                   
       </Grid.ColumnDefinitions>
    
       <SearchBar Grid.Row="0" Grid.Column="0" />
    
      </Grid>
    
    </StackLayout>