将自己创建的具有不同键名的 JSON 数组绑定到 sap.m.List

Bind self created JSON array with different key names to sap.m.List

我创建了以下 JSON 数组:

var oModel = new sap.ui.model.json.JSONModel({
  ItemSet: [
    { "item1": this.oTextBundle.getText("Flower") },
    { "item2": this.oTextBundle.getText("Tree") }
  ]
});
//then I push that model to my dialog
this._oDialog.setModel(oModel);

然后我的对话框中有一个列表,如下所示:

<List id="idList" width="700px" items="{ path:'/ItemSet'}">
  <CustomListItem>
    <Label id="id1" text="{item1}" width="350px" />
  </CustomListItem>
  <CustomListItem>
    <Label id="id2" text="{item2}" width="350px" />
  </CustomListItem>
</List>

最后绑定的唯一值来自 item2 "Tree" 的 i18n 翻译被加载到我的列表中,"Flower" 没有出现。当我切换到以下编码时:

var oModel = new sap.ui.model.json.JSONModel({
  ItemSet: [{
      "item": this.oTextBundle.getText("Flower")
    },
    {
      "item": this.oTextBundle.getText("Tree")
    }
  ]
});
//then I push that model to my dialog
this._oDialog.setModel(oModel);
<List id="idList" width="700px" items="{ path:'/ItemSet'}">
  <CustomListItem>
    <Label id="id1" text="{item}" width="350px" />
  </CustomListItem>
  <CustomListItem>
    <Label id="id2" text="{item}" width="350px" />
  </CustomListItem>
</List>

所以所有 JSON 对象中的键名必须相同?或者有没有办法用数组中的不同键按照我想要的方式实现它?

您可以为 ID 使用一个键,为 [=14= 使用另一个键,而不是尝试在您的模型中使用不同的键].

一个例子:

var oModel = new sap.ui.model.json.JSONModel({
  ItemSet: [
    { "value": this.oTextBundle.getText("Flower"), "id": "1" },
    { "value": this.oTextBundle.getText("Tree"), "id": "2" }
  ]
}); 
this._oDialog.setModel(oModel);

这样你仍然有每个条目的密钥标识符,你可以轻松地将模型绑定到你的 sap.m.List:

<List mode="SingleSelectMaster" items="{ path:'/ItemSet'}" selectionChange="listPress">
  <CustomListItem>
    <Label text="{value}"/>
  </CustomListItem> 
</List>

然后您将能够使用此方法获得所选项目的ID

listPress: function (oControlEvent) {
   var oCtx = oControlEvent.getSource().getBindingContext();
   var oPressedItem = this.getView().getModel().getProperty(oCtx.getPath());
}

oPressedItem.id 将为您提供所选项目的 ID

您提供了所需的两项,而不是为您的列表绑定提供模板。 Sapui5 期望模板是一个且唯一的控件,当提供多个时,它只采用最新的。 在您的情况下,您最终得到的是 item2,仅仅是因为模板中的第二个对象引用了 item2。

按照上面的建议,将您的视图更改为:

<List id="idList" width="700px" items="{/ItemSet}">
  <CustomListItem>
    <Label text="{item}" width="350px" />
  </CustomListItem>
</List>

它会起作用

编辑:List 的隐式聚合是 'items'。这意味着上面的代码严格等同于

<List id="idList" width="700px" items="{/ItemSet}">
  <items>
    <CustomListItem>
      <Label text="{item}" width="350px" />
    </CustomListItem>
  </items>
</List>

并且由于您绑定了 'items' 聚合,sapui5 会将 'items' 标签内的任何内容视为模板