简体   繁体   English

如何将ID附加到ListViewItem?

[英]How do I attach an id to a ListViewItem?

In my latest project, I have a ListView that is bound to an ObservableCollection . 在我的最新项目中,我有一个绑定到ObservableCollectionListView This ObservableCollection contains a number of objects of my class SongData : 这个ObservableCollection包含许多我的类SongData的对象:

public class SongData
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Artist { get; set; }
}

These objects are filled with data derived from a SQLite database, and the property Id contains the primary key for that record. 这些对象填充有从SQLite数据库派生的数据,并且属性Id包含该记录的主键。 Obviously, I don't want to show this id in my ListView. 显然,我不想在ListView中显示此ID。 However, I do need this id when I handle a DoubleClick event on the ListView. 但是,当我在ListView上处理DoubleClick事件时,确实需要此ID。

My current xaml code is: 我当前的xaml代码是:

<ListView Margin="12,41,12,12" Name="lvwOverview" SelectionMode="Single" ItemsSource="{Binding SongCollection}" MouseDoubleClick="lvwOverview_MouseDoubleClick">
     <ListView.View>
        <GridView>
            <GridViewColumn Width="200" Header="Title" DisplayMemberBinding="{Binding Title}"></GridViewColumn>
            <GridViewColumn Width="200" Header="Artist" DisplayMemberBinding="{Binding Artist}"></GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

Now, I would like to be able to get the id (for use with the database), when the user doubleclicks on a ListViewItem. 现在,当用户双击ListViewItem时,我希望能够获得ID(供数据库使用)。 Any ideas on how to do that? 关于如何做到这一点的任何想法?

In your double-click handler, you should be able to get a reference to the item that was double-clicked (or work your way to it). 在双击处理程序中,您应该能够获得对双击项的引用(或按自己的方式进行操作)。 That's the same SongData reference that was bound to. 这就是绑定到的相同SongData引用。

Just because it wasn't shown doesn't mean that the property doesn't exist anymore. 仅仅因为未显示它并不意味着该属性不再存在。 It should be there ready and available for use. 它应该在那里准备就绪并且可以使用。

Try 尝试

var data = List.SelectedItem as SongData;
if (data != null)
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM