Вопрос

I'm trying to list out data from a local database to a list box for 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>

Getting value from my database

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

I'm not really sure if the method i'm using is correct, please guide me. Thanks!

Это было полезно?

Решение

You have defined properties in your class, you have filled your List<Fruit> with items. What you should else do is (if you haven't done it already):

Define your List<Fruit> as ItemsSource of Listbox

public void ListFruit()
{
  using (var db = new SQLite.SQLiteConnection(this.DBPath))
  {
      List<Fruits> retrievedTasks = db.Table<Fruits>().ToList<Fruits>();
      myListbox.ItemsSource = retrievedTasks; // or directly
  }
} 

You may also think of using ObservableCollection instead of List - in this case you need to set ItemsSource only once - for example in constructor of the Page. You may also think of implementing INotifyPropertyChanged so that you can inform View when item changes.

And I'm not sure if you had defined Binding in your xaml (or somewhere else):

<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>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top