在ContentPage上动态居中ContentView

时间:2019-07-11 20:42:25

标签: xamarin xamarin.forms

以下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>

产生以下结果...

enter image description here

如何更改此XAML,即使大小改变,红框仍位于应用程序的整个屏幕上?

2 个答案:

答案 0 :(得分:1)

在MainPage.xaml

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

在ContentView.xaml中

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

答案 1 :(得分:0)

您可以使用StackLayout进行此操作。

不是为CenterView定义大小的重要性。

要使其垂直居中,请使用VericalOptions="Center"

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