How to use the ListView.itemDataSource in a MVVM way? RRS feed

  • Question

  • I'm looking to how to use the ListView control in a proper way with the MVVM pattern. 

    My main concern is that I would like to bind the itemDataSource to the DataContext declaratively in the view (.html). In Silverlight / wpf/ ..., I can bind the property with "{Binding Path=myPropertyInViewModel}" in the xaml where myPropertyInViewModel is a property of the actual DataContext.

    For the javascript ListView, I have found no sample on how to do this. They always use a global datasource, and I really would like to avoid that pattern.

    Let's say i have this (simplified) view model for the current page :

        var SampleViewModel = WinJS.Class.define(function () {
            this.aproperty = "a value";
        }, {
            setValues: function (someArray) {
                myPropertyInViewModel = new WinJS.Binding.List(someArray);
        WinJS.Class.mix(SampleViewModel, WinJS.Binding.mixin, WinJS.Binding.expandProperties({ aproperty: 0, myPropertyInViewModel:0 }));

    And it's binded using :

                var dataContext = new SampleViewModel();
                WinJS.Binding.processAll(element, dataContext);

    And here is what I'm trying to do. I also tryied with data-win-bind (without success).

    <div data-win-control="WinJS.UI.ListView" data-win-options="{itemDataSource: myPropertyInViewModel, itemTemplate: select('#MyDataTemplate') }"></div>

    So is it possible to bind my itemDataSource to my datacontext? If so, what is the syntax?


    Thursday, June 7, 2012 9:59 PM


  • I finally found how to and it's actually pretty simple. In case it can help someone else :

    <div data-win-control="WinJS.UI.ListView" data-win-bind="winControl.itemDataSource: myPropertyInViewModel" data-win-options="{itemTemplate: select('#MyDataTemplate')}"></div>

    • Marked as answer by Instriker Wednesday, June 13, 2012 6:36 PM
    • Edited by Instriker Wednesday, June 13, 2012 6:38 PM Sample code best fit with previous post
    Wednesday, June 13, 2012 6:35 PM