user3007447
user3007447

Reputation: 400

Loading a listbox with database items (LINQ) (Windows Phone)

edit: updated code

I'm having trouble understanding how to load data from my database into a List or collection and bind it to a ListBox.

This is in my ViewModel.

// List of Album set as the data source for Listbox
private ObservableCollection<Album> _albums;
public ObservableCollection<Album> Albums
{
    get { return _albums; }
    set { _albums = value; NotifyPropertyChanged(); }
}

        private void AddAlbum()
    {
        albumDB.Albums.InsertOnSubmit(new Album
        {
             AlbumName = AlbumName,
             AlbumTimeStamp = DateTime.Now,
             IsPrivate = IsPrivate,
             Password = Password
        });
        SaveChangesToDB();
        LoadAlbums();
    }

    private void LoadAlbums()
    {
        Albums = new ObservableCollection<Album>(albumDB.Albums);

    }

XAML

<ListBox x:Name="AlbumList">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <ListBox ItemsSource="{Binding Albums}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding AlbumName}"></TextBlock>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

I don't think I need to post the model but if so I can!

Upvotes: 0

Views: 352

Answers (2)

Charan Ghate
Charan Ghate

Reputation: 1394

You can do this

<ListBox x:Name="AlbumList" ItemsSource="{Binding Albums}">
<ListBox.ItemTemplate>
    <DataTemplate>
         <TextBlock Text="{Binding AlbumName}"></TextBlock>
    </DataTemplate>
</ListBox.ItemTemplate>

all the best :)

Upvotes: 0

Chris Shao
Chris Shao

Reputation: 8231

You can change your DataTemplate like this:

<DataTemplate>
    <TextBlock Text="{Binding AlbumName}"></TextBlock>
</DataTemplate>

Because the DataContext of ListBox.ItemTemplate is Album. So what you should do is bind AlbumName to your TextBlock, but not AlbumModel.AlbumName.

Upvotes: 1

Related Questions