Read the Value of an Item in a listbox

情到浓时终转凉″ 提交于 2019-12-08 12:00:44

问题


I'm developing a small windows store application in C# where I have populated the values and content for a listbox using the following code snippet.

code 1 : adds the song title as a item to a listbox, using the Song class to create the item

    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
    }

code 2 : Song class which is used to set values to each item ('songItem')

public class Song
{
    public string Text { get; set; }
    public int Value { get; set; }
    public override string ToString()
    {
        return Text;
    }
}

Population content to the listbox is functioning currently.

What I want is to get the 'Value' of each item on a Click event, on run-time.

For that purpose, how can I read(extract) the Value of the selected Item in the listbox, in C#? ( Value is the songItem.Value )

code 3 : I have tried this code, as trying to figure out a solution, but it didn't work

 private void listbox1_tapped(object sender, TappedRoutedEventArgs e)
        {
           Int selectedItemValue = listbox1.SelectedItem.Value();
        }

Therefore it would be really grateful if someone can help me, as I'm an Amateur.


回答1:


not sure about the "TappedRoutedEventArgs", but I would do

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

because SelectedItem is an Object (which doesn't know about the Value property), so you have to cast it to a Song first.

By the way, Value is a property, not a method, so you don't need the parenthesis.




回答2:


Try like this:

Song song=listbox1.SelectedItem as Song;

or this:

 var selected = listbox1.SelectedValue as Song;



回答3:


Try something like this :

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


来源:https://stackoverflow.com/questions/18322242/read-the-value-of-an-item-in-a-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!