When calling the MessagingCenter.Send function from a button click, it's not triggering the Subscribe method in MainActivity.cs. Need to call the DisplayMessage() in MainActivity.cs from the Button click of MainPage.xaml.cs. What is missing in this code ?
Below is the code which I used.
MainPage.xaml.cs
public partial class MainPage : ContentPage{
public MainPage()
{
InitializeComponent();
}
[Obsolete]
private void Button1_Clicked(object sender, EventArgs e)
{
MessagingCenter.Send<String>("user_name", "Message_text");
// MessagingCenter.Send<MainPage>(this, "Hi");
}
}
Subscribe in MainActivity.cs under Platforms\Android folder.
[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity{
//[Obsolete]
public override void OnCreate(Bundle savedInstanceState, PersistableBundle persistentState)
{
base.OnCreate(savedInstanceState, persistentState);
Toast.MakeText(this, "OnCreate", ToastLength.Long).Show();
MessagingCenter.Subscribe<String>(this, "Message_text", (value) =>
{
DisplayMessage(value);
});
}
private void DisplayMessage(string value)
{
Toast.MakeText(this, "Message Text = " + value, ToastLength.Long).Show();
}
}
Please try the following code:
MainActivity.cs
On
MainPage.xaml
,add a button to send message ,just as follows:Note:
1.Please add your code into method
not method
2.From Publish and subscribe to messages, we know that
MessagingCenter
has been deprecated in .NET 7 and replaced withWeakReferenceMessenger
. So, you can use Messenger instead.