在网格单元格中垂直对齐BoxView

时间:2019-02-02 21:38:47

标签: xaml xamarin xamarin.forms

使用以下布局和样式,BoxView不会垂直居中,以使其与标签对齐。我该如何实现?

<Grid Grid.Column="1">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="10" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <BoxView Grid.Column="0" BackgroundColor="Red"></BoxView>
    <Label Grid.Column="1" x:Name="lbl1"/>
</Grid>

<Style TargetType="BoxView">
    <Setter Property="WidthRequest" Value="10" />
    <Setter Property="HeightRequest" Value="10" />
    <Setter Property="VerticalOptions" Value="Center" />
    <Setter Property="HorizontalOptions" Value="Center" />
</Style>
<Style TargetType="Label">
    <Setter Property="FontSize" Value="12" />
    <Setter Property="YAlign" Value="Center" />
</Style>

enter image description here

设置VerticalOptionsStartEnd具有针对分别的顶部或底部的框平齐。因此,它似乎没有被正确地做中央对准。

4 个答案:

答案 0 :(得分:0)

改为使用CenterAndExpand

<Style TargetType="BoxView">
    <Setter Property="WidthRequest" Value="10" />
    <Setter Property="HeightRequest" Value="10" />
    <Setter Property="VerticalOptions" Value="CenterAndExpand" />
    <Setter Property="HorizontalOptions" Value="Center" />
</Style>

更新:Here's很好地说明了区别。

希望这会有所帮助。-

答案 1 :(得分:0)

1)尝试添加显式的RowDefinition及其高度;

2)尝试将标签的FontSize调整为BoxView大小;

肮脏的黑客:您可以在BoxView中添加上边距。

答案 2 :(得分:0)

您也需要在标签上使用它:

<Setter Property="VerticalOptions" Value="Center" />

您的代码只是对齐标签内的文本位置,而不是标签本身的位置。

答案 3 :(得分:0)

当文字不垂直对齐时:

  1. 尝试以下操作:设置标签

VerticalOptions="Fill"

VerticalTextAlignment="Center"
  1. 请考虑以下情况:您的元素是垂直对齐的,但由于字体创建者设置的缘故似乎不是这样,字体为底部或顶部中断对齐增加了更多空间。这可以通过自定义渲染器系统解决,也可以通过愚蠢的方式解决

    TranslationY="1"

"-0.5"等等。