简体   繁体   中英

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

How do I change variables and call functions between files in 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:

// 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.

In 2.3.6, you'll even be able to set a x:FieldModifier and modify the field values directly.

But don't do any of that. Use a Mvvm pattern, Bind your Pages, and let the ViewModels communicate between each other. 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. For example:

I have a view called 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM