Reputation: 5643
I can't seems to get databinding to work between my WinJS View code and my Windows Runtime Component ViewModel code. Any suggestions or pointers to sites where this is talked about?
I'm coming from a Xaml/C# background, but needing to make my UI (aka Views) HTML/WinJS. So I'm treating the HTML/WinJS as a View similar to the Xaml + C#-Codebehind. But I want everything else to be written using C# code. Therefore, I'm making my ViewModels from a Windows Runtime Component project and setting a local variable in the WinJS to represent an instance of the ViewModel. However, when I try to bind to a simple string property on the ViewModel, I get the following javascript exception:
Exception is about to be caught by JavaScript library code at line 8652, column 17 in ms-appx://microsoft.winjs.1.0/js/base.js 0x800a13d5 - JavaScript runtime error: Cannot define property '_getObservable': object is not extensible File: base.js, Line: 8652, Column: 17
Here is the code in my home.js file that gets the ViewModel instance and processes the bindings:
(function () {
"use strict";
var _viewModel;
WinJS.UI.Pages.define("/pages/home/home.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
// TODO: Initialize the page here.
_viewModel = ViewModels.ViewModelLocator.viewModelTest;
WinJS.Namespace.define("Application.Pages.Home", { "ViewModel": _viewModel });
WinJS.Binding.processAll(null, Application.Pages.Home.ViewModel);
}
});
})();
And here is the simple home.html code with the data-win-bind attribute:
<section aria-label="Main content" role="main" data-win-bindsource="Application.Pages.Home">
<h2 data-win-bind="innerText: ViewModel.testString"></h2>
<h3>Test String Property: <span data-win-bind="innerText: testString"></span></h3>
<button id="changeTestStringButton">Change testString value</button>
</section>
Upvotes: 2
Views: 784
Reputation: 3167
In WinJS the only objects/properties that are bindable are those that are marked as Observable using the WinJS API. This is similar to how data binding works in XAML/C# in that you need to implement INotifyPropertyChanged.
Since the WinRT object you've created is sealed, you cannot extend it to make it observable in the context that you're desiring as far as my understanding goes.
The way I've accomplished this in the past is to create JavaScript wrapper classes that handle converting to and from the WinRT types as necessary (for us, making data service calls from managed code).
Upvotes: 3