在列表框中读取项目的值
我正在使用C#开发一个小型Windowsapp store应用程序,其中我使用以下代码片段填充了列表框的值和内容 。
代码1:使用Song 类创建项目 ,将歌曲标题作为项目添加到列表框中
private void addTitles(string title, int value) { Song songItem = new Song(); songItem.Text = title; songItem.Value = value; listbox1.Items.Add(songItem); // adds the 'songItem' as an Item to listbox }
代码2:用于为每个项目设置值的Song 类 (’songItem’)
public class Song { public string Text { get; set; } public int Value { get; set; } public override string ToString() { return Text; } }
列表框的人口内容目前正在运行。
我想要的是在运行时获取Click事件上每个项目的“Value”。
为此,我如何在C#中读取(提取) 列表框中所选项的值 ? (值是songItem.Value)
代码3:我尝试过这个代码,试图找出解决方案,但它没有用
private void listbox1_tapped(object sender, TappedRoutedEventArgs e) { Int selectedItemValue = listbox1.SelectedItem.Value(); }
因此,如果有人可以帮助我,我会非常感激,因为我是业余爱好者。
不确定“TappedRoutedEventArgs”,但我会这样做
private void listbox1_tapped(object sender, TappedRoutedEventArgs e) { var selectedSong = (Song)listbox1.SelectedItem; if (selectedSong != null) { var val = selectedSong.Value; } }
因为SelectedItem
是一个Object
(它不知道Value
属性),所以你必须先将它强制转换为Song
。
顺便说一句, Value
是property
,而不是method
,因此您不需要括号。
试试这样:
Song song=listbox1.SelectedItem as Song;
或这个:
var selected = listbox1.SelectedValue as Song;
尝试这样的事情:
if (listbox1.SelectedRows.Count>0){ Song song=(Song)listbox1.SelectedItem; int value=song.Value; }