0

I'm working on my first MAUI app. It consists of two screens, switchable via a tab control.

Now to my issue - I have page MainPage.xaml with MainPage.xaml.cs and also AboutPage.xaml with AboutPage.xaml.cs.
Is there a way how to access an element of AboutPage.xaml from MainPage.xaml.cs?

My goal is, when I press a button on MainPage.xaml, I want to write a text on AboutPage.xaml, so that it's there when user switches to AboutPage via the tab.

In my AboutPage.xaml, I have

<Label 
    x:Name="textBox1"
    x:FieldModifier="public"
    Text="This a test app." />

Then, in MainPage.xaml.cs I would like to do something like

 private void OnCounterClicked(object? sender, EventArgs e)
 {
     count++;
     changeAboutText();
 }

public void changeAboutText()
{
    var aboutPage = new AboutPage();
    aboutPage.textBox1.Text = "hello";
}

This does not say any errors when building, but it does not change the text to "hello" on the AboutPage.

Any ideas?

Thanks a lot in advance for any hint!

BR, Martin

6
  • 3
    Are you familiar with MVVM? I would recommend a singleton view model (e.g. GlobalViewModel) that you inject (through DI/CI) into both pages. Commented Nov 17 at 21:25
  • I agree with the above comment. I would have a main view model for the MainPage and within the main view model, you will have sub view models for the sub pages (AboutPage etc). That way any logic that occurs in the main page can be propogated down through each child page. Shouldn't be too hard to accomplish but you would need to be familiar with basic MVVM to get started. Commented Nov 17 at 22:20
  • Add a public static in AboutPage.cs to points to "itself" via the constructor. eg. public static AboutPage Current = null; .... (in constructor) Current = this; You can then access AboutPage via AboutPage.Current. | public method or property | Commented Nov 17 at 23:43
  • @GerrySchmitz Thank you for the hint. I've tried this and I can access the elements of AboutPage from the code of MainPage.xaml.cs, but when I run the app, the text is still not changed. Commented Nov 18 at 6:26
  • 1
    What @StephenQuan said is the way to go. You should avoid using hacky solutions. Commented Nov 18 at 9:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.