【问题标题】:Filling a combobox with a dictionary as datasource when it uses uint and a custom class使用 uint 和自定义类时,用字典作为数据源填充组合框
【发布时间】:2015-11-01 07:51:48
【问题描述】:

也许有人知道如何让它发挥作用:

我的程序是一个 dll,它被另一个程序使用并从那里获取它的信息。

字典声明如下:

public Dictionary<uint, Skill> Skills { get; }

类技能声明如下:

    public class Skill
{
    public Skill(uint id, string name, string description, ushort levelRequired);

    public string Description { get; }
    public uint Id { get; }
    public ushort LevelRequired { get; }
    public string Name { get; }
}

我的目标是让我的组合框用技能名称填充它,并使用 ID 作为我通过“SelectedItem”获得的值

希望有人可以帮助我解决这个问题,我相信我尝试了 50 多种我在网上和这里找到的不同方法...

问候

【问题讨论】:

    标签: c# class dictionary combobox


    【解决方案1】:

    为什么你有 uint 作为字典键,据我所知,类中的相同 uint?

    您可以尝试将“ItemsSource”属性绑定到您的 Dictionary(或 Dictionary.Values),然后将“DisplayMemberPath”属性绑定到“Name”,并使用“SelectedValuePath”将 ID 设置为值。

    SelectedValuePath
    DisplayMemberPath

    【讨论】:

      【解决方案2】:
      public class Item
          {
              public string Name;
              public uint Value;
      
              public Item(string name, uint value)
              {
                  Name = name; Value = value;
              }
              public override string ToString()
              {
                  // Generates the text shown in the combo box
                  return Name;
              }
          }
      
       public Dictionary<uint, Skill> Skills = new Dictionary<uint, Skill>();
       private void FormTesting_Load(object sender, EventArgs e)
              {
      
      
                  Skill tempSkill= new Skill();
                  tempSkill.Name = "test name";
                  Skills.Add(1, tempSkill);
      
                  foreach (uint val in Skills.Keys)
                  {
                      comboBox1.Items.Add(new Item(Skills[val].Name,val));
                  }
              }
      

      希望对你有所帮助。

      【讨论】:

        猜你喜欢
        • 2021-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多