问题
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