中的列表布局WinJS.UI.ListView
不支持不同高度的项目;它必须是一个特定的高度。如果您需要该布局,您将不得不自己创建它。根据您的数据源和项目数量,这要么是微不足道的,要么是困难的。:)
那说明:
- 列表视图确实支持每个项目的不同模板。该
itemTemplate
属性允许您提供一个函数。详情在这里
- 基于某些属性和计算,网格布局确实支持不同大小的项目。细节在这里,最后
如果您有小数据集(<50),那么您可以自己动态创建元素,并使用 childdiv
的自然流一个接一个地堆叠您的元素。这个解决方案的种子可以在我的回答中找到。
让我扩展示例控件,基于 VS 中的“空白”WWA 项目
将此代码添加到您的default.js
:
WinJS.Namespace.define("Samples", {
ItemsControl: WinJS.Class.define(function (element, options) {
this.domElement = element;
WinJS.UI.setOptions(this, options);
}, {
domElement: null,
_dataSource: null,
dataSource: {
get: function () {
return this._dataSource;
},
set: function (v) {
this._dataSource = v;
this._renderItems(v);
}
},
pickTemplate: function (item) {
// The tempalte is found in the WinJS.Binding.Template instances that are
// in default.html. They have ID attributes on them. We're going to pick
// which one we want by setting the ID we're looking for, and then getting
// that element from the DOM and returning the winControl
var templateId = "template1"
if (item.isType2) {
// Because this is "isType2", we're going to use the other template
templateId = "template2";
}
return document.getElementById(templateId).winControl;
},
_renderItems: function (source) {
// This function renders all the items, thus when you set the datasource, and
// expect it to render items, you probably would like all your items to replace
// any existing items.
WinJS.Utilities.empty(this.domElement);
source.forEach(function (item) {
var newElement = document.createElement("div");
this.domElement.appendChild(newElement);
this.pickTemplate(item).render(item, newElement);
}.bind(this));
}
}),
});
function makeContent() {
var data = [
{ label: "First", },
{ label: "Second", },
{ label: "Third", isType2: true },
{ label: "Fourth", isType2: true },
{ label: "Fifth", },
{ label: "Sixth", isType2: true }
];
var control = document.getElementById("itemsControl").winControl;
control.dataSource = data;
}
并将内容替换为body
:
<div data-win-control="WinJS.Binding.Template"
id="template1">
<div class="type1"
data-win-bind="textContent: label"></div>
</div>
<div data-win-control="WinJS.Binding.Template"
id="template2">
<div class="type2"
data-win-bind="textContent: label"></div>
</div>
<button onclick="makeContent()">Make Content</button>
<div id="itemsControl"
data-win-control="Samples.ItemsControl">
</div>
最后,在 default.css 中:
.type1 {
background-color: green;
height: 50px;
width: 100px;
}
.type2 {
background-color: red;
height: 100px;
width: 100px;
}