John Livermore
John Livermore

Reputation: 31343

Xamarin Forms CollectionView issue

I have what should be a simple issue. However, I can't see what the problem is.

Take the following basic code to show a list of items in a CollectionView (full source available here). I am using XF 4.3.0.908675.

App.xaml.cs

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

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

        MainPage = authPage;
    }
}

LoginPage.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>

LoginPageModel.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; }
}

When this page opens, it should show the CollectionView with a list of 3 animals. On both platforms, nothing displays on the page.

Upvotes: 0

Views: 168

Answers (1)

Jason
Jason

Reputation: 89204

you are populating your VM after binding. If you move the population to the constructor, then the data will be available when the binding occurs

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

alternately, you could use an ObservableCollection instead of a List, so the UI will be notified when that data changes

Upvotes: 5

Related Questions