Xamarin Forms CollectionView 问题

Joh*_*ore 0 xamarin xamarin.forms

我有什么应该是一个简单的问题。但是,我看不出问题是什么。

使用以下基本代码显示 CollectionView 中的项目列表(此处提供完整源代码)。我正在使用 XF 4.3.0.908675。

应用程序.xaml.cs

public partial class App : Application
{
    public App()
    {
        InitializeComponent();

        var authPage = FreshPageModelResolver.ResolvePageModel<LoginPageModel>();

        MainPage = authPage;
    }
}
Run Code Online (Sandbox Code Playgroud)

登录页面.xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="SampleApp.LoginPage">

        <CollectionView Grid.Row="0"
                        ItemsSource="{Binding Animals}"
                        VerticalOptions="FillAndExpand"
                        Margin="10,0,10,0"
                        SelectionMode="None">
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Label Text="{Binding Name}" TextColor="Black" />
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>

</ContentPage>
Run Code Online (Sandbox Code Playgroud)

登录页面模型.cs

public class LoginPageModel : FreshBasePageModel
{
    protected override void ViewIsAppearing(object sender, EventArgs e)
    {
        base.ViewIsAppearing(sender, e);

        Animals = new List<Animal>();
        Animals.Add(new Animal() { Name = "Ape" });
        Animals.Add(new Animal() { Name = "Bear" });
        Animals.Add(new Animal() { Name = "Cat" });
    }

    public List<Animal> Animals { get; set; }
}

public class Animal
{
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

当此页面打开时,它应该显示带有 3 只动物列表的 CollectionView。在两个平台上,页面上都没有显示任何内容。

Jas*_*son 5

绑定填充 VM 。如果将人口移动到构造函数中,那么在绑定发生时数据将可用

    public LoginPageModel()
    {
        Animals = new List<Animal>();
        Animals.Add(new Animal() { Name = "Ape" });
        Animals.Add(new Animal() { Name = "Bear" });
        Animals.Add(new Animal() { Name = "Cat" });
    }
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用 anObservableCollection而不是 a List,以便在数据更改时通知 UI