从列表视图中获取数据

时间:2013-06-09 17:38:25

标签: c# sqlite listview windows-8 windows-runtime

我从我的sqlite数据库

填充我的listview
private async void getBowlers()
{
    SQLiteAsyncConnection conn = new SQLiteAsyncConnection(BOWLERS_DATABASE);

    var query = conn.Table<Bowler>();
    var result = await query.ToListAsync();

    List<String> names = new List<String>();

    foreach (var item in result)
    {
        names.Add(item.Name); 
    }

    itemListView.ItemsSource = names;
}

当我点击列表中的某个项目时,如何获取与所点击的项目相关联的数据?

因为我只是用字符串列表填充列表,所以我真的不知道如何将任何数据与它相关联,那么是否有另一种方法来填充我的listview?即使只是获得ID也没关系,我可以根据ID

进行查询

1 个答案:

答案 0 :(得分:0)

您可以将ListView绑定到对象,而不仅仅是字符串。如果这样做,当单击某个项目时,您将返回该对象。在您的情况下,您可以绑定到Bowler对象,我假设该对象具有IDName字段:

public class Bowler
{
    public int Id { get; set; }
    public string Name { get; set; }
}

在您的XAML中,您必须告诉ListView您要绑定Name字段。这是一个简单的ListView,每个项目只有TextBlock

<ListView x:Name="itemListView" ItemsSource="{Binding}"  
 IsItemClickEnabled="True" ItemClick="itemListView_ItemClick">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"></TextBlock>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

在上文中,TextBlock将显示Name字段。

要将项目加载到列表中,您可以将上述方法更改为:

// Unrelated, but generally you want to use "async Task" 
// in the method signature. "async void" should only be used by
// event handlers, such as a click event.
private async Task getBowlers()
{
    SQLiteAsyncConnection conn = new SQLiteAsyncConnection(BOWLERS_DATABASE);

    var query = conn.Table<Bowler>();
    var result = await query.ToListAsync();

    // set page's data context to bowler collection
    this.DataContext = result;
}

现在,当单击某个项目时,您将返回相关的Bowler对象:

private void itemListView_ItemClick(object sender, ItemClickEventArgs e)
{
    Bowler bowler = (Bowler)e.ClickedItem;
    // do something with bowler...
}

更多信息:Windows 8 Metro App ListView Binding and Editing