如何获得合适的 ComboBox 标签

How to get the appropriate ComboBox Tag

我正在尝试通过这种方式获取与 ComboBox 的值关联的标签:

var league = ((ComboBoxItem)this.League.SelectedValue).Tag.ToString();
Console.WriteLine(league);

编译器显示 Invalid Cast Exception

我只想获取用户 selected 值的关联标签,特别是:

(组合框值和标记)

-意大利(物品)- 10(标签)
-法国(物品)- 12(标签)

如果用户select意大利,在代码中我必须得到"10"。但是我做不到,我做错了什么?

更新(填充组合):

List<RootObject> obj = JsonConvert.DeserializeObject<List<RootObject>>(responseText);

        foreach (var item in obj)
        {
            foreach (var code in nation_code)
            {
                if (code.Equals(item.League))
                {
                    League.Items.Add(item.Caption);
                    //link for each team
                    League.Tag = item.Links.Teams.href;
                }
            }
        }

如果您看到标签是为组合框本身设置的,而不是为其单个项目设置的。

您可以构建字典并将其用作组合框的数据源。用字典键和值属性指定组合框的值和显示成员

尝试按如下方式修改组合填充逻辑 -

        List<RootObject> obj = JsonConvert.DeserializeObject<List<RootObject>>(responseText);
        Dictionary<string, string> comboSource = new Dictionary<string, string>();

        foreach (var item in obj)
        {
            foreach (var code in nation_code)
            {
                if (code.Equals(item.League))
                {
                    comboSource.Add(item.Caption, item.Links.Teams.href);

                }
            }
        }

        League.ValueMember = "Value";
        League.DisplayMember = "Key";
        League.DataSource = comboSource;

然后可以使用 selectedText 和 selectedvalue 属性获取所需的值。

     League.SelectedText; //Return the "item.Caption"
     League.SelectedValue; //Return the "item.Links.Teams.href" 

For WPF we need to use different properties viz. ItemsSource, DisplayMemberPath and SelectedValuePath while binding the combo box. The above solution is for win forms.

你可以添加任何类型的对象到ComboBox,它不需要是一个字符串,它只需要覆盖.ToString()。

你可以定义一个 class:

class League {
  public string Country { get; set; }
  public int Id { get; set; }

  public override string ToString() {
       return Country;
  }
}

然后将这些对象添加到 ComboBox:

comboBox.Items.Add(new League { Country = "France", Id = 10 });

然后您可以将组合框的 SelectedItem 投射回您的 class:

var selectedLeague = (League)comboBox.SelectedItem;
//access selectedLeague.Country;
//access selectedLeague.Id;