在列表框中显示多个本地数据库值
本文关键字:数据库 列表 显示 | 更新日期: 2023-09-27 18:03:11
我正试图从本地数据库列出数据到WP8.1的列表框
.xaml:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<Image Source= "**Fruit Image**" Height="26" Width="50" Margin="12,10,9,0" VerticalAlignment="Top"/>
<TextBlock Text="**Fruit Name**" FontSize="26" Style="{StaticResource BodyTextBlockStyle}"/>
<TextBlock Text="**Fruit Colour**" FontSize="26" Style="{StaticResource BodyTextBlockStyle}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
从我的数据库获取值
cs:
public void ListFruit()
{
using (var db = new SQLite.SQLiteConnection(this.DBPath))
{
List<Fruits> retrievedTasks = db.Table<Fruits>().ToList<Fruits>();
}
}
cs
public class Fruits
{
public string ImgPath { get; set; }
public string FruitName { get; set; }
public string FruitColour{ get; set; }
}
我不确定我使用的方法是否正确,请指导我。谢谢!
您已经在类中定义了属性,您已经用项目填充了List<Fruit>
。你应该做的是(如果你还没有做的话):
将List<Fruit>
定义为Listbox的ItemsSource
public void ListFruit()
{
using (var db = new SQLite.SQLiteConnection(this.DBPath))
{
List<Fruits> retrievedTasks = db.Table<Fruits>().ToList<Fruits>();
myListbox.ItemsSource = retrievedTasks; // or directly
}
}
您也可以考虑使用ObservableCollection
而不是List
-在这种情况下,您只需要设置一次ItemsSource
-例如在Page的构造函数中。你也可以考虑实现INotifyPropertyChanged
,这样你就可以在项目发生变化时通知View。
我不确定你是否在你的xaml(或其他地方)定义了绑定:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<Image Source= "{Binding ImgPath}" Height="26" Width="50" Margin="12,10,9,0" VerticalAlignment="Top"/>
<TextBlock Text="{Binding FruitName}" FontSize="26" Style="{StaticResource BodyTextBlockStyle}"/>
<TextBlock Text="{Binding FruitColour}" FontSize="26" Style="{StaticResource BodyTextBlockStyle}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>