在 Xamarin.Forms 3.5 中,Microsoft 向我们介绍了可绑定(bind)布局,可用于动态填充布局(例如 StackLayout
、 Grid
等)。
在具有单列的网格中使用它非常简单:
<Grid BindableLayout.ItemsSource="{Binding Items}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Label Text="{Binding MyProperty}"/>
</DataTemplate>
</BindableLayout.ItemTemplate>
</Grid>
现在我的问题是,由于
DataTemplate
,如何使用它来填充多列的网格。只允许 一 视为内容。当然我可以,但另一个 Grid
在其中,但这将使 Grid
中可绑定(bind)布局的值完全无效。 .
最佳答案
Now my question is how this can be used to populate a grid with more than one column due to the fact that DataTemplate only allows one view as content.
来自 Bindable Layouts , 我们可以看到:
虽然在技术上可以将可绑定(bind)布局附加到从 Layout 类派生的任何布局类,但这样做并不总是可行,特别是对于 AbsoluteLayout、Grid 和 RelativeLayout 类。例如,考虑使用可绑定(bind)布局在 Grid 中显示数据集合的场景,其中集合中的每个项目都是一个包含多个属性的对象。网格中的每一行都应显示集合中的一个对象,网格中的每一列都显示该对象的一个属性。由于可绑定(bind)布局的 DataTemplate 只能包含一个对象,因此该对象必须是包含多个 View 的布局类,每个 View 在特定的 Grid 列中显示对象的一个属性。虽然可以使用可绑定(bind)布局来实现此场景,但它会导致父 Grid 为绑定(bind)集合中的每个项目包含一个子 Grid,这是对 Grid 布局的一种非常低效且有问题的使用。
如果你还想要更多的列,我建议你可以使用 StackLayout,它也可以满足你的要求。
<StackLayout BindableLayout.ItemsSource="{Binding persons}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding name}" />
<Label Text="{Binding age}" />
</StackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
关于xamarin - 如何使用具有可绑定(bind)布局的网格(多于一列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57711507/