【问题标题】:c# windows 8 selected comboboxitem时间:2019-05-10 标签:c#windows 8 selected comboboxitem
【发布时间】:2013-04-24 16:24:23
【问题描述】:

我正在开发一个 Windows 8 应用商店应用程序 (c#)。 我有一个从存储库中获取项目的组合框 (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)中获取组合框选择值??

【问题讨论】:

    标签: c# windows-8 combobox


    【解决方案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() 以返回描述。在这种情况下,您的原始代码应该可以正常工作。

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

    【讨论】:

    • 哇,我怎么没看到这个:) 非常感谢!!
    • 如何检查从 cboTeam1 中选择的项目是否与从 cboTeam2 中选择的项目不同?
    • 最好将其作为一个新问题提出。 :)
    猜你喜欢
    • 2020-06-15
    • 2020-10-01
    • 2015-06-14
    • 2011-07-08
    • 2012-02-03
    • 2017-04-15
    • 2021-07-31
    • 2016-01-27
    • 1970-01-01
    相关资源
    最近更新 更多