[英]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. 这是在我的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 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! 我认为我不需要发布模型,但是如果可以的话!
You can change your DataTemplate like this: 您可以像这样更改您的DataTemplate :
<DataTemplate>
<TextBlock Text="{Binding AlbumName}"></TextBlock>
</DataTemplate>
Because the DataContext
of ListBox.ItemTemplate is Album . 因为ListBox.ItemTemplate的
DataContext
是Album 。 So what you should do is bind AlbumName to your TextBlock, but not AlbumModel.AlbumName. 因此,您应该做的是将AlbumName绑定到您的TextBlock,而不是AlbumModel.AlbumName。
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 :) 祝一切顺利 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.