如何通过main-page.js更改基于xml的textField的文本?我使用this.set("message", getMessage(this.counter));
通过main-view-model.js更改值。但是当我在main-page.js中尝试它时,这种情况不起作用。这该怎么做? :-)我需要解释一下我的主要问题。提前谢谢。
答案 0 :(得分:1)
我假设你在谈论" Hello World"可以找到here的NativeScript应用程序。区别在于main-page.js是" 背后的代码" main-page.xml的注意事项(注意命名约定对于{N}进行匹配很重要)和main-view-model.js是一个单独的文件,已被分配为bindingContext
到Page你可以看到here:
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的Label(TextView)文本,您可以通过id(getViewById()
example)或直接获取Label使用bindingContext
(您的&#39; ViewModel&#39;):
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");
}