2013-04-24 69 views
0

我正在開發Windows 8商店應用程序(c#)。 我有一個Combobox(cboTeam1),它從存儲庫中獲取項目。c#windows 8選擇comboboxitem

private static List<TeamItem> JPLItems = new List<TeamItem>(); 

public static List<TeamItem> getJPLItems() 
    { 
     if (JPLItems.Count == 0) 
     { 
      JPLItems.Add(new TeamItem() { Id = 1, Description = "Anderlecht", Image = "Jpl/Anderlecht.png", ItemType = ItemType.JPL }); 
      JPLItems.Add(new TeamItem() { Id = 1, Description = "Beerschot", Image = "Jpl/Beerschot.png", ItemType = ItemType.JPL }); 
      JPLItems.Add(new TeamItem() { Id = 1, Description = "Cercle Brugge", Image = "Jpl/Cercle.png", ItemType = ItemType.JPL }); 
      JPLItems.Add(new TeamItem() { Id = 1, Description = "Charleroi", Image = "Jpl/Charleroi.png", ItemType = ItemType.JPL }); 
     } 
     return JPLItems; 
    } 

我加載項在cboTeam1的的ItemsSource:

cboTeam1.ItemsSource = ItemRepository.getJPLItems(); 

當cboTeam1的SelectionChanged我這樣做:

private void cboTeam1_SelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 
     Ploeg1.Text = cboTeam1.SelectedValue.ToString();    
    } 

這導致:SportsBetting.Model.TeamItem

任何人都可以幫我拿到組合框selectedvalue在我的文本塊(Ploeg1.Text)??

回答

1

你幾乎已經爲自己回答了這個問題。

private void cboTeam1_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
     // cast the selected item to the correct type. 
    var selected = cboTeam.SelectedValue as TeamItem; 
     //then access the appropriate property on the object, in this case "Description" 
     // note that checking for null would be a good idea, too. 
    Ploeg1.Text = selected.Description;    
} 

另一種選擇是覆蓋TeamItem類中的ToString()以返回Description。在這種情況下,你的原代碼應該可以正常工作

public override string ToString() 
{ 
    return this._description; // assumes you have a backing store of this name 
} 
+0

哇,爲什麼我沒有看到這個:) 非常感謝! – user1951083 2013-04-24 08:29:14

+0

如何檢查cboTeam1中選定的項目是否與cboTeam2中的選定項目不同? – user1951083 2013-04-24 09:32:41

+0

可能最好問這個問題。 :) – ZombieSheep 2013-04-24 11:30:59