[英]Xamarin Forms - Access variable in another page
I have a function in my MainPage.xaml.cs, and when it is called I would like to change the text on a label in another page called Dashboard.xaml.cs 我的MainPage.xaml.cs中有一个函数,当它被调用时,我想更改另一个页面Dashboard.xaml.cs中标签上的文本。
How do I change variables and call functions between files in Xamarin Forms? 如何在Xamarin Forms中的文件之间更改变量和调用函数?
Pages are just classes, and you can communicate between them like any class: using public methods, public properties, public events, etc 页面只是类,您可以像任何类一样在页面之间进行通信:使用公共方法,公共属性,公共事件等
However, using Form's built in MessagingCenter might be the best method: 但是,使用MessagingCenter内置的Form可能是最好的方法:
// send a message TO an instance of MyPage
MessagingCenter.Send<MyPage, string> (this, "MessageName", some_string_arg);
// in MyPage, listen for the Message
MessagingCenter.Subscribe<MyPage> (this, "MessageName", (sender, args) => {
// args will contain the value passed in Send
});
Provided that you have a reference to the instance of the Page, you can invoke methods or set properties on that instance. 如果您具有对Page实例的引用,则可以在该实例上调用方法或设置属性。
In 2.3.6, you'll even be able to set a x:FieldModifier
and modify the field values directly. 在2.3.6中,您甚至可以设置
x:FieldModifier
并直接修改字段值。
But don't do any of that. 但是不要做任何事情。 Use a Mvvm pattern, Bind your Pages, and let the ViewModels communicate between each other.
使用Mvvm模式,绑定页面,并让ViewModel之间相互通信。 And your Pages will be modified accordingly.
并且您的页面也会相应地修改。
Every view in Xamarin is a class, you can instantiate a variable of the type View, where View is the page you want to access. Xamarin中的每个视图都是一个类,您可以实例化View类型的变量,其中View是您要访问的页面。 For example:
例如:
I have a view called Works. 我有一个称为Works的视图。 To access (public) functions and variables contained within the view, I write code like this:
要访问视图中包含的(公共)函数和变量,我编写如下代码:
Works MyTestVariable;
var SomeResult = MyTestVariable.FunctionInWorksClass(aParameter);
The function contained in the Works view is executed and the value is returned to the var in the calling view. 将执行Works视图中包含的函数,并将该值返回给调用视图中的var。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.