【问题标题】:Key/Value pairs in ComboBox using Delphi Firemonkey使用 Delphi Firemonkey 在 ComboBox 中的键/值对
【发布时间】:2017-09-26 15:03:11
【问题描述】:

我想使用枚举器来填充带有键/值对的组合框。对用户隐藏密钥并仅显示值很重要。在选择时,我想捕获与所选值关联的键。

代码看起来与此类似。

var
    currentObj: ISuperObject; 
    enum: TSuperEnumerator<IJSONAncestor>;

    while enum.MoveNext do
    begin

        currentObj := enum.Current.AsObject;
        cboUserList.Items.Add(currentObj.S['key'],currentObj.S['value']);

    end;

currentObj.S['key'] 应该在用户选择值时被捕获 currentObj.S['value']cboUserList 下拉列表中对用户可见。

有什么想法吗?

【问题讨论】:

  • 不要让 GUI 控件管理程序的数据结构。

标签: delphi combobox firemonkey


【解决方案1】:

一个简单的跨平台解决方案是使用单独的TStringList 来保存keys,然后在组合框中显示values,并使用其项目索引来访问TStringList 项目。

var
  currentObj: ISuperObject;
  enum: TSuperEnumerator<IJSONAncestor>;

while enum.MoveNext do
begin
  currentObj := enum.Current.AsObject;
  userSL.Add(currentObj.S['key']);
  cboUserList.Items.Add(currentObj.S['value']);
end;

var
  index: Integer;
  key: string;
begin
  index := cboUserList.ItemIndex;
  key := userSL[index];
 ... 
end;

【讨论】:

    【解决方案2】:

    您可以将密钥包装在类中,例如

    type
      TKey = class
        S: string;
        constructor Create(const AStr: string);
      end;
    
    constructor TKey.Create(const AStr: string);
    begin
      S := AStr;
    end;
    
    procedure TForm2.Button2Click(Sender: TObject);
    begin
      ComboBox1.Items.AddObject('value', TKey.Create('key'));
    end;
    

    然后访问它

    procedure TForm2.ComboBox1Change(Sender: TObject);
    begin
      Caption := (ComboBox1.Items.Objects[ComboBox1.ItemIndex] as TKey).S;
    end;
    

    请确保稍后销毁这些对象

    【讨论】:

    • 我会避免使用可视化组件作为业务逻辑的一部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    相关资源
    最近更新 更多