【发布时间】:2021-02-03 01:07:43
【问题描述】:
在我的 Xamarin Forms 应用程序中,我有一个字符串列表(最少 1 个,最多 4 个),我想在列布局中均匀显示。每列需要具有相同的宽度,并且内容应该扩展,以便整个文本被包裹并且可见。我知道如何使用Grid 控件在其列上使用Width="*" 来做到这一点。
我想使用FlexLayout 获得相同的结果,因此我可以将字符串列表绑定到BindableLayout 并轻松添加和删除列(我不会显示字符串,而是在每列中显示更复杂的布局)。
使用FlexLayout.Grow 和FlexLayout.Basis 我可以让FlexLayout 显示大小均匀的列。问题是使FlexLayout 的高度适合所有显示的标签。只显示第一行文本。
Grid 和 FlexLayout 都包含在 StackLayout 中:
<StackLayout>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Text="First label" Grid.Column="0" BackgroundColor="Aqua"
LineBreakMode="WordWrap" />
<Label Text="Second label" Grid.Column="1" BackgroundColor="Red"
LineBreakMode="WordWrap" />
<Label Text="Third label but with longer text" Grid.Column="2" BackgroundColor="Aqua"
LineBreakMode="WordWrap"/>
<Label Text="Fourth label" BackgroundColor="Red"
Grid.Column="3" LineBreakMode="WordWrap" />
</Grid>
<BoxView BackgroundColor="Blue"></BoxView>
<FlexLayout AlignItems="Stretch">
<Label Text="First label"
FlexLayout.Grow="1"
FlexLayout.Basis="0"
BackgroundColor="Aqua"
LineBreakMode="WordWrap" />
<Label Text="Second label"
FlexLayout.Grow="1"
FlexLayout.Basis="0"
BackgroundColor="Red"
LineBreakMode="WordWrap" />
<Label Text="Third label but with longer text"
FlexLayout.Grow="1"
FlexLayout.Basis="0"
BackgroundColor="Aqua"
VerticalOptions="FillAndExpand"
LineBreakMode="WordWrap" />
<Label Text="Fourth label"
FlexLayout.Grow="1"
FlexLayout.Basis="0"
BackgroundColor="Red"
LineBreakMode="WordWrap" />
</FlexLayout>
<BoxView BackgroundColor="Blue"></BoxView>
</StackLayout>
我发现当将 FlexLayout 的 HeightRequest 设置为特定数字(例如 150)时,一切都按预期工作 - 行的高度为 150,所有标签都伸展以适应该数字。所以我需要以某种方式指定HeightRequest="Auto",以便该行适合所有列的内容而不设置为特定值
有没有办法做到这一点?
【问题讨论】:
-
您可能需要在FlexLayout中为FlexLayout或Label设置hightRequest,或者只使用Grid,别想其他办法了。
-
当您已经有了网格解决方案时,为什么还要探索 Flex
-
@ShubhamTyagi 出于我所描述的原因:网格迫使我提前声明所有列 (XAML),或者让我在后面的代码中动态定义所有标记。 FlexLayout 将允许我将 IEnumerable 绑定到 BindableLayout 并通过 DataTempalte 为单个列定义一个模板
标签: xaml xamarin xamarin.forms