2013-08-19 37 views
0

我開發C#中的小窗戶商店應用程序,我已經填充內容使用下面的代碼片段一個列表框讀取的物品的價值在ListBox

代碼1:添加歌曲標題作爲列表框,使用樂曲創建

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:宋這是用於設定每個項目的值項目('歌曲項目')

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(); 
     } 

因此這將是如果有人真的感謝可以幫助我,因爲我是一個業餘愛好者。

回答

4

不知道的 「TappedRoutedEventArgs」,但我會做

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

因爲SelectedItemObject(它不知道Value屬性),所以你必須投我t先到Song

順便說一句,Valueproperty,而不是method,所以你不需要括號。

+0

欣賞的響應,我通過鑄造價值爲int修改了給定的代碼,並得到預期的結果。 – hirosht

0

嘗試這樣的:

Song song=listbox1.SelectedItem as Song; 

或本:

var selected = listbox1.SelectedValue as Song; 
0

嘗試這樣:

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