Search code examples
c#xamarin.androidvisual-studio-mac.net-maui

Pass data between two Content Page;


I am fairly new to programming in Maui. Previously, I wrote android applications in Xamarin. I have question. How to transfer variables between two Content Page. I try this way:

I have two content page, MainPage and SettingsPage. This is how I send data to SettingsPage:

public async void goToSettingsPage_button_Clicked(object sender, EventArgs e)
{
  await Navigation.PushAsync(new DetailsPage(language));
}

And this is how I perceive them:

public partial class SettingsPage : ContentPage
{
public SettingsPage(string language)
{
    InitializeComponent();
   
    String Language = language;
}
}

I just used Intent on xamarin. PutExtra or Intent.GetExtra. I don't know how to work in Maui. How to pass a variable back from SettingsPage to MainPage. I tried to do it in the same way as above;


Solution

  • You can use the MessagingCenter to send the data to the other pages. Also, you can send the data back in the same way.

    First, you can send message to the subscriber in the viewmodel of MyWordPage.Xalm.cs, just as follows:

    private void Button_Clicked(object sender, EventArgs e)
    {
          MessagingCenter.Send<MainPage, String>(this, "language", English);
    }
    

    Second, in the viewmodel of MainPage, you can subscribe the message and here is the code :

    public class MainPageViewModel: INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged(string propertyName)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
            public String mylanguage = "asd" ;
            public String Mylanguage {
                get
                {
                    return mylanguage;
                }
                set
                {
                    if(mylanguage != value)
                    {
                        mylanguage = value;          
                        OnPropertyChanged(nameof(Mylanguage));
                    }
                }
            }
            public MainPageViewModel()
            {
                MessagingCenter.Subscribe<MainPage, Sring>(this, "language", (sender, arg) =>
                {
                    Mylanguage = arg;
                });
            }
        }
    

    At last,we can bind the mylanguage to the label in the MainPage.xaml :

    <Label Text="{Binding mylanguage} "  ></Label>
    

    More information you can refer to Publish and subscribe to messages.