listview - Xamarin 将网格绑定到 ListView 中的 ViewCell
问题描述
我动态地(必须是动态的)在代码中构建一个 Grid,并希望 Grid 成为 ListView 中唯一的东西。创建 Grid 的代码工作正常(经过测试),但现在我想将 Grid 放在 ListView 中,这样我就可以使用 ListView 的“下拉刷新”功能。
我的代码如下所示:
// ... Build the Grid
// Set the item source of the ListView to this one Grid
MatrixCells.ItemsSource = new ObservableCollection<Grid>(new List<Grid> { grid });
我的 Xaml 看起来像这样:
<ListView
x:Name="MatrixCells"
IsPullToRefreshEnabled="True"
RefreshCommand="{Binding ReloadProjectCommand}"
IsRefreshing="{Binding IsLoading, Mode=OneWay}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<!-- WHAT GOES HERE ?? -->
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
我的问题是如何将 ListView 中的整个项目绑定到我创建的网格?请参阅“这里发生了什么??”。
我试过了:
<Grid BindingContext="{Binding}" />
我知道这没有意义......还有其他一些事情,但无法让网格显示。有任何想法吗?
谢谢。
解决方案
由于您有一个可观察的集合Grid
,因此在ViewCell
将网格列表添加到 ViewCells View 属性中,如下所示,确保您 的 ListView 属性中有HasUnevenRows="True" :
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell View="{Binding .}"/>
</DataTemplate>
</ListView.ItemTemplate>
编辑
我刚查了一下,看来 View 不是可绑定的属性,给您带来的不便请见谅……
您可以做的是从 C# 端创建 DataTemplate 并将其分配给 ListView,如下所示:
public class WithDataTemplatePageCS : ContentPage
{
public WithDataTemplatePageCS()
{
...
var people = new List<Person>
{
new Person { Name = "Steve", Age = 21, Location = "USA" },
...
};
var personDataTemplate = new DataTemplate(() =>
{
var grid = new Grid();
...
var nameLabel = new Label { FontAttributes = FontAttributes.Bold };
var ageLabel = new Label();
var locationLabel = new Label { HorizontalTextAlignment = TextAlignment.End };
nameLabel.SetBinding(Label.TextProperty, "Name");
ageLabel.SetBinding(Label.TextProperty, "Age");
locationLabel.SetBinding(Label.TextProperty, "Location");
grid.Children.Add(nameLabel);
grid.Children.Add(ageLabel, 1, 0);
grid.Children.Add(locationLabel, 2, 0);
return new ViewCell { View = grid };
});
Content = new StackLayout
{
Margin = new Thickness(20),
Children = {
...
new ListView { ItemsSource = people, ItemTemplate = personDataTemplate, Margin = new Thickness(0, 20, 0, 0) }
}
};
}
}
有关这方面的更多信息,请查看Micorsoft 文档
推荐阅读
- arrays - 在 SAS 中使用数组、循环和条件语句来获取数据中指定起始位置的校验累积和
- python - list index out of range error when I want fit a model in keras
- reactjs - 成功按钮后如何自动刷新页面
- angularjs - 如何将空文件推送到github?
- c - C 语言:scanf 和 sscanf 表达式
- php - CodeIgniter4 - 使用数据重定向
- javascript - JS 音频在加载后从特定设置的时间跳回 0
- azure-functions - 带有 POST HTTP 触发器的 Azure Functions 无明显原因返回代码 500
- python - 这种类型错误的解决方案是什么:列表索引必须是整数或切片,而不是 str?
- android - 如何设计 android 微调框?