简体   繁体   中英

A method to add an element to a ListView

Is there a method to add an element to a ListView? My goal is to do this without binding data! For example:

     myListView.add("one");
     myListView.add("two");

ecc

Just simply add the item to your initial list. If you have binding setup, this happens automatically.

Html

<div id="simpleBinding" data-win-control="WinJS.UI.ListView"></div>

<div id="simpleBindingTemplate" data-win-control="WinJS.Binding.Template">
    <h3 data-win-bind="innerText:name" />
    <span>Name :</span><span data-win-bind="textContent: name"></span>
    <img data-win-bind="src:imageUrl" />
</div>

Javascript



//Note you could also declare an object type to use here,
//and instantiate them in the list below 
var Person = WinJS.Binding.define({
    name: "",
    birthday: ""
});

//Using the above object
//var people = [
//    new Person({ name: "Bob", birthday: "2/2/2002" }),
//    new Person({ name: "Sally", birthday: "3/3/2003" }),
//    new Person({ name: "Fred", birthday: "2/2/2002" })
//];


//Or simply using JSON
var people = [{ name: 'mary', birthday: '1/1/2010' }, 
              { name: 'fred', birthday: '1/1/2012' }];

//create the binding wrapper
var simpleFriends = new WinJS.Binding.List(people);

//get the ref to your list view
var simpleListView = document.getElementById('simpleBinding').winControl;

//get your template
var simpleTemplate = document.getElementById('simpleBindingTemplate');

simpleListView.itemDataSource = simpleFriends.dataSource;
//can also set in the markup for this element
simpleListView.itemTemplate = simpleTemplate;


//add a new item. the binding update happens automatically
//Could use a Person object we defined
//simpleFriends.push(new Person({ name: "Dynamically added", birthday: "2/2/2002"}));

//or JSON
simpleFriends.push({ name: "Dynamically added", birthday: "2/2/2002"});

For removing items you can use pop or check out this post for an indexed approach Removing an item from a WinJS.Binding.List

There's some good binding content on App Builder for 'Day 10' App Builder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM