Xamarin Forms CollectionView issue



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

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

应用xaml.cs

public partial class App : Application
{
public App()
{
InitializeComponent();
var authPage = FreshPageModelResolver.ResolvePageModel<LoginPageModel>();
MainPage = authPage;
}
}

登录页面.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>

登录页面模型.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; }
}

当此页面打开时,它应该显示包含 3 种动物列表的 CollectionView。 在这两个平台上,页面上不显示任何内容。

绑定填充 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" });
}

或者,您可以使用ObservableCollection而不是List,因此当数据更改时将通知 UI

最新更新