How to use MessagingCenter correctly?

axbeitaxbeit Member ✭✭
edited January 22 in Xamarin.Forms

Hello. Im using Xamarin.Forms Crossplatform with .NET library if that matters.

App.xaml.cs

MainPage = new NavigationPage(new MainPage());

MainPage.xaml.cs

Im using a method here. I have a TapGestureRecognizer on a Frame:

void OnTestTapped(object sender, EventArgs args)
{
//...
MessagingCenter.Send<MainPage, string>(this, "Message", "TryThis");
Navigation.PushAsync(new AnotherPage());
}

AnotherPage.xaml

<StackLayout>
<Label x:Name="labelName"/>
</StackLayout>

AnotherPage.xaml.cs:

public partial class AnotherPage : ContentPage
{
    string helper;
    public AnotherPage()
    {
        InitializeComponent();
        MessagingCenter.Subscribe<MainPage, string>(this, "Message", (sender, helper) =>
        {
            this.helper = helper;
            labelName.Text = this.helper;
        });
    }
}

When Debugging I can see that label.Text has a value of "TryThis". But when looking on the App there is no text. Where is my mistake here and how can I fix it?

Best Answers

Answers

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    Stop.

    <Label x:Name="labelName"/>
    labelName.Text = this.helper;
    Before you go any further and drive these bad 1998 WinForms concepts into your head... Just stop.

    Don't try to write your own app before learning foundation concepts for designing your app - like MVVM. You really need to work on the simple stuff like binding a label long before you work on higher end stuff like MessagingCenter.

    http://redpillxamarin.com/2018/03/12/2018-101-vs2017-new-solution/

Sign In or Register to comment.