Home > database >  Why can't I use properties from my ObservableCollection inside a ListView
Why can't I use properties from my ObservableCollection inside a ListView

Time:12-28

I'm trying to return an Observablecollection, what seems to be fine. When I want to get the properties of each item in the collection, I get the error "Binding: Property '' not found on".

I have the following code:
I removed all markup code, to make it easier to read

View

<ListView ItemsSource="{Binding Books}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Grid>
                    <Label Text="{Binding Title}" />
                    <Label Text="{Binding Description}" />
                    <Label Text="{Binding Date}" />
                </Grid>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

ViewModel

public class BookListPageViewModel : ViewModelBase
{
    private ObservableCollection<Book> _books = new();
    public ObservableCollection<Book> Books
    {
        get => _books;
        set => SetProperty(ref _books, value);
    }
}

Model

public class Book : ModelBase
{
    public string Title { get; set; }
    public string Description { get; set; }
    public string Date { get; set; }
}

The weird thing is, earlier I had the class Book inside the ViewModel file and that did work. But I want this class to be in the Models folder.
This is how my ViewModel looked like before.

namespace Some.Namespace.Project
{
    public class Book : ModelBase
    {
        public string Title { get; set; }
        public string Description { get; set; }
        public string Date { get; set; }
    }

    public class BooksListPageViewModel : ViewModelBase
    {
        private ObservableCollection<Book> _books = new();
        public ObservableCollection<Book> Books
        {
            get => _books;
            set => SetProperty(ref _books, value);
        }
    }
}

How is it that the Bindings (Title, Description, and Date) are not found?

CodePudding user response:

I'm new to XAML and apparently it's possible to add your own x-tags in the ContentPage.

So in my ContentPage I added xmlns:models="clr-namespace:Namespace.To.Models".
With this tag I can change my DataTemplate to <DataTemplate x:DataType="models:Book">.

This solved the problem for me.

  • Related