我正在开发Windows 8商店应用程序(c#)。 我有一个Combobox(cboTeam1)从存储库中获取项目。
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选择改变时,我这样做:
private void cboTeam1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Ploeg1.Text = cboTeam1.SelectedValue.ToString();
}
这导致: SportsBetting.Model.TeamItem
任何人都可以帮助我在我的文本块(Ploeg1.Text)中获取组合框选择值吗?
答案 0 :(得分: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
}