首页 > 解决方案 > 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}" />

我知道这没有意义......还有其他一些事情,但无法让网格显示。有任何想法吗?
谢谢。

标签: listviewxamarinxamarin.forms

解决方案


由于您有一个可观察的集合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 文档


推荐阅读