0

如何通过 main-page.js 更改基于 xml 的 textField 的文本?我使用this.set("message", getMessage(this.counter));通过 main-view-model.js 更改值。但是当我在 main-page.js 中尝试时,这种情况不起作用。这个怎么做?:-) 我需要解释我的主要问题。提前致谢。

4

1 回答 1

1

我假设您谈论的是可以在此处找到的“Hello World”NativeScript 应用程序。不同之处在于main-page.js是main -page.xml的“代码后面” (注意命名约定对于 {N} 进行匹配很重要),而 main-view-model.js 是如您在此处看到的,在其 navigatingTo 事件中已分配给 main-page.xml 页面的单独文件:bindingContext

function onNavigatingTo(args) {
    /*
    This gets a reference this page’s <Page> UI component. You can
    view the API reference of the Page to see what’s available at
    https://docs.nativescript.org/api-reference/classes/_ui_page_.page.html
    */
    var page = args.object;

    /*
    A page’s bindingContext is an object that should be used to perform
    data binding between XML markup and JavaScript code. Properties
    on the bindingContext can be accessed using the {{ }} syntax in XML.
    In this example, the {{ message }} and {{ onTap }} bindings are resolved
    against the object returned by createViewModel().
    You can learn more about data binding in NativeScript at
    https://docs.nativescript.org/core-concepts/data-binding.
    */
    page.bindingContext = createViewModel();
}

为了在其代码隐藏文件中更改 main-page.xml 的标签(TextView)的文本,您可以通过 id(getViewById() 示例)或直接使用bindingContext(您的“ViewModel”)获取标签:

var createViewModel = require("./main-view-model").createViewModel;
var viewModel;

function onNavigatingTo(args) {
    var page = args.object;
    viewModel = = createViewModel();
    page.bindingContext = viewModel;
}

// Example with event handler for a 'tap' event of a Button
function onButtonTap(args) {
    viewModel.set("message", "New message set via code behind");
}
于 2016-12-07T12:56:09.497 回答