在列表框中读取项目的值

时间:2013-08-19 20:10:03

标签: c# listview listbox windows-store-apps

我正在使用以下代码在C#中开发一个小型Windows应用商店应用,其中我为列表框填充了内容片段。

代码1:将歌曲标题添加为项目列表框,使用Song 创建项目< / em>的

    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 class ,用于为每个项设置值('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();
        }

因此,如果有人可以帮助我,我会非常感激,因为我是业余爱好者。

3 个答案:

答案 0 :(得分:4)

不确定&#34; TappedRoutedEventArgs&#34;,但我会这样做

private void listbox1_tapped(object sender, TappedRoutedEventArgs e)
        {
           var selectedSong = (Song)listbox1.SelectedItem;
           if (selectedSong != null) {
              var val = selectedSong.Value;
              }
        }

因为SelectedItemObject(它不知道Value属性),所以你必须先将其Song。< / p>

顺便说一下,Valueproperty,而不是method,因此您不需要括号。

答案 1 :(得分:0)

试试这样:

Song song=listbox1.SelectedItem as Song;

或者这个:

 var selected = listbox1.SelectedValue as Song;

答案 2 :(得分:0)

尝试这样的事情:

if (listbox1.SelectedRows.Count>0){
      Song song=(Song)listbox1.SelectedItem;
  int value=song.Value;
}