Xamarin.Forms 中心列表查看项目

Sco*_*rod 1 xaml xamarin.forms

如何在 Xamarin.Forms 应用程序中居中显示列表视图项目?列表视图项目当前左对齐。我希望它们居中对齐。

我有以下代码:

    <ListView Grid.Row="1" Grid.Column="0" ItemsSource="{Binding Results}" HorizontalOptions="Center">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.View>
                        <Grid HorizontalOptions="Center">
                            <Grid.RowDefinitions>
                                <RowDefinition />
                            </Grid.RowDefinitions>

                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="auto" />
                                <ColumnDefinition Width="auto" />
                            </Grid.ColumnDefinitions>

                            <Label Grid.Row="0" Grid.Column="0" Text="{Binding FirstName}" />
                            <Label Grid.Row="0" Grid.Column="1" Text="{Binding LastName}" />
                        </Grid>
                    </ViewCell.View>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
Run Code Online (Sandbox Code Playgroud)

Dav*_*vid 5

Scott 网格始终会扩展以占据 100% 的可用空间。据我所知,没有办法覆盖这个,即使在网格上显式设置宽度请求似乎也没有帮助。

我假设您有一个更大的布局要求,您试图满足在 listView 中居中放置名字和姓氏,使用 Stacklayout 而不是网格可以更好地完成。IE

<ViewCell.View>    
<StackLayout Orientation="Horizontal">
    <Label Text="{Binding FirstName}" HorizontalOptions="EndAndExpand"/>
    <Label Text="{Binding LastName}" HorizontalOptions="StartAndExpand"/>
</StackLayout>
</ViewCell.View>
Run Code Online (Sandbox Code Playgroud)

但假设您确实需要一个网格,那么我只能对 Tomasz 的建议提供 1 个补充。

<Grid>
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition />
<ColumnDefinition/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="1" Text="{Binding FirstName}" HorizontalOptions="End"/>
<Label Grid.Row="0" Grid.Column="2" Text="{Binding LastName}" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

这会在外部创建两列,以占用空间,迫使名称位于中间。