John Livermore
John Livermore

Reputation: 31313

Dynamically centering a ContentView on a ContentPage

The following XAML...

MainPage.xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:SampleApp"
             x:Class="SampleApp.MainPage">

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <local:CenterView Grid.Column="1" />
    </Grid>

</ContentPage>

ContentView.xaml

<ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="SampleApp.CenterView">
    <ContentView.Content>
            <BoxView BackgroundColor="Red" 
                     HorizontalOptions="Start"
                     VerticalOptions="Start"
                     HeightRequest="100" 
                     WidthRequest="100" />
    </ContentView.Content>
</ContentView>

Produces the following result...

enter image description here

How can this XAML be changed so the red box centers on the entire screen of the app even when it's size changes?

Upvotes: 0

Views: 487

Answers (2)

Lucas Zhang
Lucas Zhang

Reputation: 18861

in MainPage.xaml

<Grid>
 <Grid.ColumnDefinitions>
  <ColumnDefinition Width="*" />
  <ColumnDefinition Width="Auto" />
  <ColumnDefinition Width="*" />
 </Grid.ColumnDefinitions>
 <local:CenterView Grid.Column="1" />
</Grid>

in ContentView.xaml

<BoxView BackgroundColor="Red" 
         HorizontalOptions="CenterAndExpand"
         VerticalOptions="CenterAndExpand"
         HeightRequest="200" 
         WidthRequest="200" />

Upvotes: 1

Alen.Toma
Alen.Toma

Reputation: 4870

You could do this with StackLayout.

Not that its importend to define a size for CenterView.

To center it vertical, Use VericalOptions="Center".

<StackLaout>
  <local:CenterView HorizontalOptions="Center" HeightRequest="100" WidthRequest="100" />
</StackLayout>

Upvotes: 0

Related Questions